python - 为什么 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/
解决方案
open(path,'w')
path
如果文件不存在,肯定会创建文件,但前提是路径中的所有目录都已存在。也就是说,它会创建一个文件,但不会创建目录。
(此外,除非您对将在其中创建文件的目录具有写权限,否则它无法创建文件。但这会给您带来不同的错误消息。)
推荐阅读
- matlab - 从matlab图中获取模拟深度图像
- r - 如何控制条形图中类别之间的空间?
- docker - 在 ECS 上使用自定义配置的 Traefik
- c++ - vcpkg-built google protobuf 和 grpc 不会静态链接到应用程序
- javascript - 可以替换单词**即使是弹出窗口**的 Chrome 扩展程序?
- javascript - 表单在同一页面中的页面加载时自动提交一次 jQuery
- java - 有没有办法比 O(n) 更快地反转字符串?
- javascript - React:如何用多个元素的单个引用替换 .querySelectorAll
- r - 如何将 RODBC 与包含 DDL 命令的查询一起使用?
- assembly - 如何使用 Irvine32 WriteFloat 而非 printf 显示舍入为 .001 的浮点数