我想在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
如果不存在的文件是不是一個錯誤的情況下,但隨後可能的情況下檢查,並明確之前處理它的缺失/非可讀性(和*另外*到)'try'可能是值得的。這可以分別用'os.path.exists(file)'和'os.access(file,os.R_OK)'完成。這樣的檢查永遠不會出現競爭狀態,但是消失的文件很少是正常的情況;) – stefanct 2017-04-08 14:50:34
這個問題的答案可能應該更新爲包含'pathlib'模塊的使用,這使得這個問題變得更加容易,並且應該可能是標準的Python練習(特別是因爲它也回到了2.7)。 – 2017-07-03 13:56:31