【发布时间】:2015-11-08 13:25:54
【问题描述】:
我遇到了一个小问题:在 'w' 模式下使用函数 open() 时,所有文档都说如果文件不存在则创建该文件。不幸的是,在我的情况下,由于某种原因,我收到了FileNotFound 错误。
with open(newFileName, 'w') as newFile:
#CODE
我收到以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'path of file I have specified'
知道为什么会这样吗?提前致谢!
编辑:对于那些询问目录是否存在的人,我对代码做了一些小改动,可能会告诉你这确实是一条好路。
if not os.path.exists("example"):
os.makedirs("example")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
newFileName = "example/restOfPath"
newFileName = os.path.join(BASE_DIR,newFileName)
with open(newFileName, 'w') as newFile:
我仍然收到以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'correctPathToDirectory/example/restOfPath'
EDIT2:忽略这个问题,问题解决了。在“示例”之后创建了第二个目录,因此它不起作用。愚蠢的错误。
【问题讨论】:
-
你可以做一个
print(newFileName)并查看提到的文件 -
你能给我们newFileName的值吗?我怀疑它可能是例如/some/dir/filename,其中 /some/dir 不存在。
-
@WédneyYuri OP 没有要求以读写模式打开文件...
-
我确实想到了这种可能性,所以我在该行代码之前创建了目录。
标签: python file python-3.x