2017-07-20 3 views
0

xlrdを使用して ".xlsx"ファイルを開き、そこからデータを読み込んで変更します。ファイル名が存在する場合、すべてがOKです。ファイルが存在しない場合、私はトレースバックを取得します。xlrdを使用した不正なファイル名によるトレースバック

私が使用しているコードは(ちょうど関連部分)である:

私は、ファイルを開くことができるかどうかを確認するために読んで関数を使用する
from xlrd import open_workbook, XLRDError 
from xlwt import * 
filename = "./resources/tags_meters.xlsx" 
bad_filename = "./resources/meters.txt" 

# Use this to test bad filenames 
filename = bad_filename 

とafther:

def test_book(filename): 
    try: 
     open_workbook(filename) 
    except XLRDError as e: 
     print "error is" + e.message 
     return False 
    else: 
     return True 

if test_book(filename): 
    print "Book Ok ... Opening file" 
    wb = open_workbook(filename) 
else: 
    print "Book not opened" 

私が持っているトレースバックは:

Traceback (most recent call last): 
  File ".\excelread.py", line 38, in <module> 
    if test_book(filename): 
  File ".\excelread.py", line 31, in test_book 
    open_workbook(filename) 
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 395, in open_workbook 
    with open(filename, "rb") as f: 
IOError: [Errno 2] No such file or directory: './resources/meters.txt' 

なぜ例外が機能していないのですか?ファイルが存在するかどうかを知る必要があるため、私はこれをテストしています。そうでない場合は、ファイルを作成する必要があります。

+2

をあなたは 'IOError'ではなく取得しています'XLRDError' - あなたのハンドラはそれを捕まえません。 – asongtoruin

答えて

2

例外句にXLRDErrorをキャッチするだけで、ファイルが存在しない場合はIOErrorが発生します。

あなたは両方のための句を除いて同じを使用できます:あなたが異なっそれらを扱いたい場合は、

except(XLRDError, IOError): 
    #.... 

または、多分よりよい:

except XLRDError: 
    # treat this error 
    # ... 

except IOError: 
    # treat the case where file doesn't exist 
+0

ありがとう!それを見ていないために、今はかなり愚かな気分になりました。 –

関連する問題