python读取文件数据转化为字典(读取字典类型的文本和读取excel文件)
python读取文件数据转化为字典(读取字典类型的文本和读取excel文件)import xlrd# filePath:字符串,Excel文件名称# workTable:字符串,Excel文件中(sheet)表格名称def read_excel_data(file_path work_table): try: # 这里要用decode,否则中文乱码,读不到文件 data_name = xlrd.open_workbook(file_path.decode('utf8')) table = data_name.sheet_by_name(work_table.decode('utf8')) except: print '%s文件打开失败' % (file_path) return table
一,读取文本:
比如D盘有个文本文件TestConf.ini,它的内容是一个字典:{"tester":"sterson" "projectName":"baidu"}
def read_dict_conf(conf_path):
f = open(conf_path "r")
content_dict = eval(f.read())
f.close()
return content_dict
# 调用
test_config = read_dict_conf('d:\\TestConf.ini')
# 读取projectName ,读出来的值就是baidu
proName = test_config["projectName"]
二,读取excel文件
通过python读取excel里的内容,用到包 xlrd。
import xlrd
# filePath:字符串,Excel文件名称
# workTable:字符串,Excel文件中(sheet)表格名称
def read_excel_data(file_path work_table):
try:
# 这里要用decode,否则中文乱码,读不到文件
data_name = xlrd.open_workbook(file_path.decode('utf8'))
table = data_name.sheet_by_name(work_table.decode('utf8'))
except:
print '%s文件打开失败' % (file_path)
return table
test_data = read_excel_data('d:\\t.xls' 'Sheet1')
irows = test_data.nrows
for td in xrange(1 irows):
test_name = test_data.cell(td 0).value
test_sex = test_data.cell(td 1).value
test_class = test_data.cell(td 2).value
print '%s%s%s%s%s' % (test_name ' ' test_sex ' ' test_class)