首页 > 解决方案 > 为什么 open('file','w') 说文件不存在?

问题描述

我有一个功能:

def loadFile(file):
    path = script_dir + file #script_dir has the form '/home/username/blah/blah/' and file has the form 'asdf/foo.txt'
    temp = open(path,'w')
    temp.close()
    with open(path) as f:
        return f.read().replace('\n', '')

当我print(loadFile('asdf/asdf.txt'))在 python3 中运行时,出现错误:

FileNotFoundError: [Errno 2] No such file or directory: '/home/username/blah/blah/asdf/asdf.txt'

为什么会这样?我很困扰。我到处看它都说'w'会创建文件,为什么不是。

注 1:我运行 Zorin OS Education Lite(对不起,我无法为您提供更通用的术语)。
注意 2:我有一个 NTFS 分区安装在/home/username/blah/

标签: pythonpython-3.xfileubuntu

解决方案


open(path,'w')path如果文件不存在,肯定会创建文件,但前提是路径中的所有目录都已存在。也就是说,它会创建一个文件,但不会创建目录。

(此外,除非您对将在其中创建文件的目录具有写权限,否则它无法创建文件。但这会给您带来不同的错误消息。)


推荐阅读