2016-11-16 64 views
1

我觉得奇怪,我Python - with open()except(FileNotFoundError)?

with open(file, 'r') 

可以报告

FileNotFoundError: [Errno 2] 

,但我不能赶上,在某种程度上和继续。我是否在这里丢失了某些东西,或者真的希望在使用open()之前使用isfile()或类似的东西?

+0

[同时使用一个Python捕获异常“与”声明】的可能的复制(http://stackoverflow.com/questions/713794/catching-an-exception-while-using-a-python-with -声明) –

回答

2

使用try/except处理异常

try: 
    with open("a.txt") as f : 
     print(f.readlines()) 
except Exception: 
    print('not found') 
    #continue if file not found 
0
from __future__ import with_statement 

try: 
    with open(file) as f : 
     print f.readlines() 
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available 
    print('oops') 

如果你想从公开征集VS工作代码中的错误不同的处理,你可以这样做:

try: 
    f = open(file) 
except IOError: 
    print('error') 
else: 
    with f: 
     print(f.readlines()) 
0

如果您收到FileNotFound错误,问题很可能是文件名或文件路径不正确。如果您尝试读取并写入尚不存在的文件,请将模式从'r'更改为'w+'。它还可以帮助文件之前写出来的完整路径,Unix用户为:

'/Users/paths/file' 

或者更好的是,我们os.path中让你的路径可以在其他操作系统上运行。

import os 
with open(os.path.join('/', 'Users', 'paths', 'file'), 'w+)