Python3.4:使用模式'w'打开文件仍然给我FileNotFound错误

Bal*_*aam 10 python file python-3.x

我遇到一个小问题:在使用该模式的函数open()'w',所有文档都说如果文件不存在则创建该文件.不幸的是,在我看来,我FileNotFound出于某种原因出错了.

with open(newFileName, 'w') as newFile:
    #CODE
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'path of file I have specified'
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样吗?提前致谢!

编辑:对于那些询问目录是否存在的人,我对代码做了一些小改动,可能会显示它确实是一条好路径.

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:
Run Code Online (Sandbox Code Playgroud)

我仍然收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'correctPathToDirectory/example/restOfPath'
Run Code Online (Sandbox Code Playgroud)

EDIT2:无视这个问题,问题解决了.在"示例"之后创建了第二个目录,因此它无法正常工作.愚蠢的错误.

x s*_*red 16

导致此错误的原因可能是包含新文件的目录尚不存在.

open()with 'w'仅为您创建不存在的文件,但不为整个目录路径创建.所以你首先需要为文件创建目录.

  • 然后另一种可能性是您的程序在指定目录中没有写权限. (5认同)

归档时间:

查看次数:

8280 次

最近记录:

7 年,9 月 前