【发布时间】:2017-03-31 04:08:03
【问题描述】:
我觉得很奇怪
with open(file, 'r')
可以举报
FileNotFoundError: [Errno 2]
但我无法以某种方式抓住它并继续。我在这里遗漏了什么还是真的希望您在 with open() 之前使用 isfile() 或类似的东西?
【问题讨论】:
标签: python python-3.x
我觉得很奇怪
with open(file, 'r')
可以举报
FileNotFoundError: [Errno 2]
但我无法以某种方式抓住它并继续。我在这里遗漏了什么还是真的希望您在 with open() 之前使用 isfile() 或类似的东西?
【问题讨论】:
标签: python python-3.x
使用try/except处理异常
try:
with open( "a.txt" ) as f :
print(f.readlines())
except Exception:
print('not found')
#continue if file not found
【讨论】:
FileNotFoundError 或 IOError,具体取决于您的 Python 版本。
如果您收到 FileNotFound 错误,问题很可能是文件名或文件路径不正确。如果您尝试读写一个尚不存在的文件,请将模式从'r' 更改为'w+'。对于 Unix 用户来说,在文件之前写出完整路径也可能会有所帮助:
'/Users/paths/file'
或者更好的是,我们使用 os.path,以便您的路径可以在其他操作系统上运行。
import os
with open(os.path.join('/', 'Users', 'paths', 'file'), 'w+)
【讨论】: