【发布时间】:2015-02-15 00:39:05
【问题描述】:
朋友们,
我试图用 try/except 块打开一个文件。
try:
with open(finput[1], "r") as f:
for line in f:
if "NQ" in line[:2]:
nq = int(line[-3:].strip())
except EnvironmentError:
print(("Oops! File \"{:s}\" does not exist!").format(f))
# print(("Oops! File \"{:s}\" does not exist!").format(finput[1]))
sys.exit(0)
当我在 except 中使用 finput[1] 时(即现在已注释),它可以正常工作并按预期提供文件名。
但是如果我使用f(因为我试图将文件finput[1]打开为f),它会给我错误:
回溯(最近一次通话最后):
文件“readspr.py”,第 30 行,在
print(("糟糕!文件\"{:s}\"不存在!").format(f))
NameError: name 'f' is not defined
我在 python 方面没有多少经验(只知道编码,但不知道它是如何工作的。)。
所以,我对此的解释是:
因为,以f 打开文件失败,f 中没有存储任何内容;因此它是未定义的。
但是,另一方面,python 似乎会尝试以f 打开文件,因此,finput[1] 中的任何内容都作为变量字符串分配给f,python 无法打开文件f。
我不确定这里是什么情况。我试图从互联网上的许多部分(即7.2.1 of this、the accepted answer here 等)中理解它,但只是找到了我使用它的用途:simplifying exception handling。
如果您能解释为什么不将f 视为例外,这将对我有所帮助。
【问题讨论】:
标签: python-3.x