我有一个功能:
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/
最佳答案
open(path,'w')
肯定会在 path
创建文件如果它不存在,但前提是路径中的所有目录都已经存在。也就是说,它会创建一个文件,但不会创建目录。
(此外,除非您对将在其中创建文件的目录具有写权限,否则它无法创建文件。但这会给您带来不同的错误消息。)
关于python - 为什么 open ('file' ,'w' ) 说文件不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66510858/