Python自動化測試中,利用xlrd加載文件名,代碼如下:
newpath = os.chdir('文件所在目錄')
filename = "文件名.xlsx"
報IOError: [Errno 22] invalid mode ('rb') or filename:‘xxxxxxxxxxxxxxxxxxxxxxxxx’
解決此問題的方法是在腳本頭注釋 : # -*- coding: cp936 -*-
遇到的第二個問題是打印filename里面的sheet頁名字時,打印的是非中文字符,解決辦法是引用json模塊,利用json將非中文字符轉變為中文字符,
代碼如下: print (json.jump(xl.sheet_names(),ensure_ascii=False,encoding="gb2312")
為了方便大家更好的理解,將部分代碼貼出,如下:
# -*- coding: UTF-8 -*-
import os
import xlrd
import json
newpath = os.chdir('文件所在目錄')
filename = "文件名.xlsx"
file = os.path.join(os.getcwd(),filename)
xl = xlrd.open_workbook(file) #打開文件
print json.jump(xl.sheet_names(), ensure_ascii=False,encoding="gb2312") #獲取sheet頁名稱,將非中文字符轉變為中文字符