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页名称,将非中文字符转变为中文字符