繁体   English   中英

FileNotFoundError:[Errno 2] 没有这样的文件或目录:'demofile.txt'

[英]FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'

有人能告诉我为什么当我想用 python 打开一个文本文件时,我的 output 是 FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt' 即使文件已经在同一个文件夹中并且写入正确. 这是文件和文件夹

这是我的代码 f = open("demofile.txt", "r") print(f.read())

之前谢谢你

Python 文件的路径和当前工作目录可能不同。 如果您使用相对路径,则open使用当前工作目录。 显而易见的解决方法是使用绝对路径。 但是,每次将脚本复制到不同的文件夹时,您都必须编辑代码。

您可以使用pathlib根据当前正在运行的脚本位置创建绝对路径。 将其放入 Python 脚本中,运行它并查看结果。

import pathlib

print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'demofile.txt')
print(pathlib.Path(__file__).parent / 'data' / 'demofile.txt')

因此您的代码可以更改为

filepath = pathlib.Path(__file__).parent / 'demofile.txt'
with open(filepath, 'r') as f:
    print(f.read())

尝试with

with open("demofile.txt","r") as f:
    f.read()

也许,您正在使用绝对路径执行 python 文件,这就是 FileNotFound 的原因。 尝试使用绝对路径。 像, c:\files\demofile.txt

我用 Mathias 的回答解决了这个问题,我也遇到了同样的问题,但是有一张图片,那么你需要写

import pathlib

print(pathlib.Path(__file__).parent) print(pathlib.Path(__file__).parent / 'name_of_your_file.extension') print(pathlib.Path(__file__).parent / 'data' / 'name_of_your_file.extension')

已经做了正确的答案是使用文本文件所在的特定文件夹的名称非常感谢大家

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM