簡體   English   中英

使用xlrd使用錯誤的文件名進行回溯

[英]Traceback with bad filename using xlrd

我正在使用xlrd打開“ .xlsx”文件並從中讀取數據以對其進行修改。 如果文件名存在,則一切正常。 但是如果文件不存在,我會得到一個追溯。

我正在使用的代碼是(只是相關的部分):

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

另外,我使用函數讀取文件是否可以打開:

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'

為什么異常不起作用? 我正在測試它,因為我需要知道文件是否存在,如果不存在,則需要創建它。

您只能在您的except子句中捕獲XLRDError ,並且當文件不存在時會發生IOError

您可以對兩個都使用相同的except子句:

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

或者,如果您想區別對待它們,可能會更好:

except XLRDError:
    # treat this error
    # ...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM