# 第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:
#
# {
# "1":["张三",150,120,100],
# "2":["李四",90,99,95],
# "3":["王五",60,66,68]
# }
# 请将上述内容写到 student.xls 文件中,如下图所示:
import json
import xlwt
def read_txt(file):
with open(file) as f:
data = f.read()
print(type(data),data)
dic_data = json.loads(data)
print(type(dic_data),dic_data)
return dic_data
def wright_xls(dic_data,save_file):
excel = xlwt.Workbook(encoding='utf-8') # 创建excel
sheet1 = excel.add_sheet('sheet1') # 创建sheet
r = 0 # r为行数
if isinstance(dic_data,dict):
for i,j in dic_data.items():
sheet1.write(r,0,i) # 写第一列数据
if isinstance(j,list): # student.txt
for v in range(1,len(j)+1): # 写入第二列以后的数据
sheet1.write(r,v,j[v-1])
elif isinstance(j,str): # city.txt
sheet1.write(r, 1, j)
r += 1 # 行数加一
elif isinstance(dic_data,list): # 0016.txt
for line in dic_data:
if isinstance(line,list):
for i in range(len(line)):
sheet1.write(r, i, line[i])
r += 1 # 行数加一
excel.save(save_file)
if __name__ == "__main__":
dic_data1 = read_txt('student.txt') # 0014
wright_xls(dic_data1,'student.xls')
dic_data2 = read_txt('city.txt') #0015
wright_xls(dic_data2,'city.xls')
dic_data3 = read_txt('0016.txt') # 0016
wright_xls(dic_data3, '0016.xls')
student.txt
{
“1”:[“张三”,150,120,100],
“2”:[“李四”,90,99,95],
“3”:[“王五”,60,66,68]
}
city.txt
{
“1” : “上海”,
“2” : “北京”,
“3” : “成都”
}
0016.txt
[
[1, 82, 65535],
[20, 90, 13],
[26, 809, 1024]
]