小编Bal*_*aam的帖子

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

我遇到一个小问题:在使用该模式的函数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:无视这个问题,问题解决了.在"示例"之后创建了第二个目录,因此它无法正常工作.愚蠢的错误.

python file python-3.x

10
推荐指数
1
解决办法
8280
查看次数

标签 统计

file ×1

python ×1

python-3.x ×1