【问题标题】:open() does not create new file. FileNotFoundError occurs insteadopen() 不会创建新文件。而是发生 FileNotFoundError
【发布时间】:2019-10-12 12:04:55
【问题描述】:

我想在与我的 python 文件相同的目录中创建一个文本文件,但我得到了 FileNotFounfError。我认为如果文件不存在,open() 应该创建一个新文件。

我的python文件:

with open("test.txt", "w") as f:
    f.write("Test")

但我收到以下消息

Traceback (most recent call last):
  File "C:/Users/POPOVA/Desktop/Programming/Algs/Stack Overflow/myAns.py", line 1, in <module>
    with open("test.txt", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

感谢您的帮助

【问题讨论】:

    标签: python python-3.x with-statement


    【解决方案1】:

    变化:

    with open("test.txt", "w") as f:
    

    收件人:

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

    您可能还想阅读this stack overflow question。特别是这条评论:

    问题是目录。要么脚本缺乏在该目录中创建文件的权限,要么该目录根本不存在。 open('myfile.dat', 'w') 就足够了

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2012-08-15
      • 2014-04-26
      • 1970-01-01
      • 2011-02-27
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多