gpt4 book ai didi

python - 无法读取肯定存在的文件

转载 作者:行者123 更新时间:2023-12-05 07:57:31 25 4
gpt4 key购买 nike

我写了下面的代码来打开一个特定的文件。该文件肯定存在,那么为什么 Python 说没有这样的文件?

try:
fh = open("F:/EveryThing! Python/CorePython/Strings/tester.txt");
strg = fh.read();
print (strg);
except IOError, e:
print e;
print "outputting e",e.args;
finally:
print "This is bound to be executed";

这个输出:

[Errno 2] No such file or directory: 'F:/EveryThing! Python/CorePython/Strings/tester.txt'
outputting e (2, 'No such file or directory')
This is bound to be executed

最佳答案

您一定是错误地指定了文件名,因此根据 python,它并不“绝对存在”。使用 os.path.exists检查文件是否确实存在于给定位置。例如,我在运行下面代码的目录下创建了一个文件“a.txt”,但是“b.txt”不存在:

import os

print os.path.exists("a.txt")
print os.path.exists("b.txt")

try:
open("a.txt")
except IOError, e:
print e

try:
open("b.txt")
except IOError, e:
print e

这里的输出是:

> python ff.py 
True
False
[Errno 2] No such file or directory: 'b.txt'

关于python - 无法读取肯定存在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com