【问题标题】:Python open("file", "w+") not creating a nonexistent filePython open("file", "w+") 没有创建一个不存在的文件
【发布时间】:2021-12-26 08:15:22
【问题描述】:

Stack Overflow 上也存在类似问题。我已经阅读了这些问题,但它们并没有解决我的问题。下面的简单代码会导致 File Not Found 错误。我在 Mac OS X 11.4 上运行 Python 3.9.1

任何人都可以建议解决此问题的后续步骤吗?

with open("/Users/root/test/test.txt", "w+") as f:
    f.write("test")
Traceback (most recent call last):
  File "/Users/root1/PycharmProjects/web_crawler/test.py", line 1, in <module>
    with open("/Users/root/test/test.txt", "w+") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/root/test/test.txt'

【问题讨论】:

  • 尝试删除用户前面的第一个/
  • Users/root/test/ 目录是否存在?如果不是,那可能是问题所在,因此请先尝试创建该目录,然后再运行此代码。
  • 删除“用户”前面的前导“/”并未解决问题。 '/Users/root/' 是一个有效的现有目录,但 'test/' 不存在。我正在编写一个网络爬虫来将媒体下载到与作者姓名相对应的目录中,并且需要一些可以生成不存在的目录和文件的方法。有什么建议吗?我知道 os.mkdir() 可以做到这一点,但我认为 w+ 提供了相同的功能?
  • 在运行之前创建 '/test/' 将允许它按预期运行,但使用 os.mkdir() 似乎没有必要
  • 你为什么认为 open 会创建一个不存在的目录?没有记录这样做。

标签: python macos file file-io with-statement


【解决方案1】:

您在最初的帖子中阐明了您需要发生的事情。
下面假设

  • 目录Users/root1/存在
  • 您正在尝试在其中创建一个新的子目录 + 文件
import os

# Wrap this in a loop if you need
new_dir = 'test' # The variable directory name
new_path = 'Users/root1/' + new_dir + "/"
os.makedirs(os.path.dirname(new_path), exist_ok=True) # Create new dir 'Users/root1/${new_dir}/

with open(new_path + "test.txt", "w+") as f:
    # Create new file in afore created directory
    f.write("test")

这将基于变量new_dir 创建一个新目录,并在其中创建文件test.txt

【讨论】:

    【解决方案2】:

    **有时编译器找不到任何像你在 open() 函数中插入的路径。那时您可以默认保存在IDE保存程序的文件夹中。以下语法可能对您有所帮助**

    with open('test.txt', 'w+') as f:
         f.write("xyz")
    

    **此处的 text.txt 将默认保存在您的 IDE 存储您编写的程序的文件夹中。您可以检查该文件夹的构造**

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2023-03-08
      • 2011-02-27
      • 1970-01-01
      • 2021-07-22
      • 2018-11-20
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多