可能是一个非常菜鸟的问题..
但是 当我尝试时:
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
我收到错误
IOError: [Errno 2] No such file or directory: '/home/path/filename'
是不是因为我说了“w”..如果它不存在,它会写入一个新文件?
最佳答案
错误消息可以这样重现:
import os
filename = '/home/path/filename'
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
f.close()
# IOError: [Errno 2] No such file or directory: '/home/path/filename'
这里的问题是filename
是绝对路径,所以
os.path.join 忽略第一个参数并返回文件名:
In [20]: filename = '/home/path/filename'
In [21]: os.path.join(os.path.dirname(__file__), filename)
Out[21]: '/home/path/filename'
因此,您不仅指定了一个不存在的文件,还指定了一个不存在的目录。 open
拒绝创建目录。
关于python - 无法在Python中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14860381/