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'
なぜ例外が機能していないのですか?ファイルが存在するかどうかを知る必要があるため、私はこれをテストしています。そうでない場合は、ファイルを作成する必要があります。
をあなたは 'IOError'ではなく取得しています'XLRDError' - あなたのハンドラはそれを捕まえません。 – asongtoruin