为错误编写不同的语句
Writing a different statement for an error
我在 Python 中编写了一个关于文件 I/O 的程序,其中包含打开文件的部分,即
....
f = open("<filename.txt", "r")
alltext = f.readlines()
....
在找不到文件的情况下,我想写一个打印语句说,"Sorry, file not found."
我尝试使用错误处理(for & except),由于上面后面的嵌套代码,它不能很好地工作。任何帮助将不胜感激。
谢谢
使用os.path.isfile
:
https://docs.python.org/2/library/os.path.html#os.path.isfile
此外,如果您需要阅读所有文本,您可能想要这样做:
if os.path.isfile(f):
with open("filename.txt") as f
alltext = f.read()
else:
# print statement goes here
我在 Python 中编写了一个关于文件 I/O 的程序,其中包含打开文件的部分,即
....
f = open("<filename.txt", "r")
alltext = f.readlines()
....
在找不到文件的情况下,我想写一个打印语句说,"Sorry, file not found." 我尝试使用错误处理(for & except),由于上面后面的嵌套代码,它不能很好地工作。任何帮助将不胜感激。
谢谢
使用os.path.isfile
:
https://docs.python.org/2/library/os.path.html#os.path.isfile
此外,如果您需要阅读所有文本,您可能想要这样做:
if os.path.isfile(f):
with open("filename.txt") as f
alltext = f.read()
else:
# print statement goes here