2011-04-11 41 views
32

我想在Python中讀取.csv文件。嘗試在python中讀取文件時處理異常的好方法是什麼?

  • 我不知道,如果該文件存在。
  • 我現在的解決方案如下。這對我來說很sl because,因爲這兩個單獨的異常測試並不合時宜。

有更漂亮的方式做到這一點?

import csv  
fName = "aFile.csv" 

try: 
    with open(fName, 'rb') as f: 
     reader = csv.reader(f) 
     for row in reader: 
      pass #do stuff here 

except IOError: 
    print "Could not read file:", fName 
+0

如果不存在的文件是不是一個錯誤的情況下,但隨後可能的情況下檢查,並明確之前處理它的缺失/非可讀性(和*另外*到)'try'可能是值得的。這可以分別用'os.path.exists(file)'和'os.access(file,os.R_OK)'完成。這樣的檢查永遠不會出現競爭狀態,但是消失的文件很少是正常的情況;) – stefanct 2017-04-08 14:50:34

+1

這個問題的答案可能應該更新爲包含'pathlib'模塊的使用,這使得這個問題變得更加容易,並且應該可能是標準的Python練習(特別是因爲它也回到了2.7)。 – 2017-07-03 13:56:31

回答

17

我想我誤解了被問到的內容。重新閱讀,看起來蒂姆的答案就是你想要的。讓我補充這一點,但是:如果你想從open捕捉異常,然後open必須被包裹在一個try。如果調用open處於with的頭,然後with必須在try捕獲異常。這是沒有辦法的。

因此,答案可以是:「蒂姆的方式」或「不,你做正確。」


上一頁無益的答案,所有的評論是指:

import os 

if os.path.exists(fName): 
    with open(fName, 'rb') as f: 
     try: 
      # do stuff 
     except : # whatever reader errors you care about 
      # handle error 

+7

僅僅因爲一個文件存在並不意味着你可以閱讀它! – Gabe 2011-04-11 20:59:03

+1

這並不完美,因爲可能會在檢查文件存在並嘗試打開文件之間刪除文件(例如,由另一個進程刪除)。 – 2011-04-11 20:59:22

+0

也許我誤解了這個問題。其實我覺得我確實是。 – 2011-04-11 21:00:38

17

如何:

try: 
    f = open(fname, 'rb') 
except IOError: 
    print "Could not read file:", fname 
    sys.exit() 

with f: 
    reader = csv.reader(f) 
    for row in reader: 
     pass #do stuff here 
+5

唯一的問題是該文件是在'with'塊之外打開的。因此,如果包含'open'調用的'try'塊和'with'語句之間發生異常,則文件不會關閉。在這種情況下,事情非常簡單,這不是一個明顯的問題,但是在重構或修改代碼時仍然可能會造成危險。這就是說,我認爲沒有更好的方法來做到這一點(除了原始版本)。 – intuited 2011-04-11 21:12:24

+1

@intuited:是的。事實上,OP的最終答案可能只是:不,你做這件事的方式是正確的。 – 2011-04-11 21:20:36

-3

添加到@喬希的例子;

fName = [FILE TO OPEN] 
if os.path.exists(fName): 
    with open(fName, 'rb') as f: 
     #add you code to handle the file contents here. 
elif IOError: 
    print "Unable to open file: "+str(fName) 

這樣你可以嘗試打開文件,但如果它不存在(如果它引發IOError),提醒用戶!

+2

'elif IOError'?真的嗎?另請參閱@ Josh提案的評論,該評論至少可以正確地使用語法。 – delnan 2011-04-11 21:17:52

+0

沒有看到問題。如果語法不正確,它會在執行時引發語法錯誤! – 2011-04-11 21:22:20

+4

不是語法錯誤,但'bool(IOError)'只是'True','if'不會捕獲任何異常。 – delnan 2011-04-11 21:23:23

6

這裏是一個讀/寫的例子。 with語句確保close()語句將由文件對象調用,而不管是否拋出異常。 http://effbot.org/zone/python-with-statement.htm

import sys 

fIn = 'symbolsIn.csv' 
fOut = 'symbolsOut.csv' 

try: 
    with open(fIn, 'r') as f: 
     file_content = f.read() 
     print "read file " + fIn 
    if not file_content: 
     print "no data in file " + fIn 
     file_content = "name,phone,address\n" 
    with open(fOut, 'w') as dest: 
     dest.write(file_content) 
     print "wrote file " + fOut 
except IOError as e: 
    print "I/O error({0}): {1}".format(e.errno, e.strerror) 
except: #handle other exceptions such as attribute errors 
    print "Unexpected error:", sys.exc_info()[0] 
print "done" 
相關問題