2017-08-30 70 views
1

嘗試讀取文件的Pythonic方法是什麼,如果讀取此異常讀取引發異常回退以讀取替代文件?嘗試讀取文件的Pythonic方式以及異常回退到備用文件的情況

這是我寫的示例代碼,它使用嵌套try - except塊。這是pythonic:

try: 
    with open(file1, "r") as f: 
     params = json.load(f) 
except IOError: 
    try: 
     with open(file2, "r") as f: 
      params = json.load(f) 
    except Exception as exc: 
     print("Error reading config file {}: {}".format(file2, str(exc))) 
     params = {} 
except Exception as exc: 
    print("Error reading config file {}: {}".format(file1, str(exc))) 
    params = {} 

回答

1

對於兩個文件的方法在我看來不夠好。

如果你有多個文件回退到我會用一個循環去:

for filename in (file1, file2): 
    try: 
     with open(filename, "r") as fin: 
      params = json.load(f) 
     break 
    except IOError: 
     pass 
    except Exception as exc: 
     print("Error reading config file {}: {}".format(filename, str(exc))) 
     params = {} 
     break 
else: # else is executed if the loop wasn't terminated by break 
    print("Couldn't open any file") 
    params = {} 
0

您可以檢查file1是否先存在,然後決定打開哪個文件。它會縮短代碼並避免重複try -- catch子句。我相信這是更pythonic,但請注意,您需要在您的模塊import os這個工作。 它可以是這樣的:

fp = file1 if os.path.isfile(file1) else file2 
if os.path.isfile(fp): 
    try: 
     with open(fp, "r") as f: 
      params = json.load(f) 
    except Exception as exc: 
     print("Error reading config file {}: {}".format(fp, str(exc))) 
      params = {} 
else: 
    print 'no config file' 
+2

這會導致競爭條件,加上'OSError'也可能是由於'PermissionError'等 –

+0

不會吧無論如何,如果您嘗試在沒有適當的權限的情況下打開(fp,「r」)',就會得到'PermissionError'? – Vinny

0

雖然我不能完全肯定這是否是Python的或沒有,也許是這樣的:

file_to_open = file1 if os.path.isfile(file1) else file2 
相關問題