lst = []
with open('你的文件.txt', 'r') as f:
s = f.readline()
lst = eval("[" + s + "]")
print(lst[1][1]) #输出 bbb
不知道你这个问题是否已经解决, 如果还没有解决的话:.txt表格型数据如下,其中分割符为’\t’,最后通过换行符’\n’换行
我可以通过以下步骤解决该问题:
with open('file_path.txt') as f:
f.readline()
lines = f.readlines()
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i] = lines[i][:-1]
lines[i] = lines[i].split('\t')
table = []
for i in range(len(lines)):
name = lines[i][0]
score = int(lines[i][1]) * 0.5 + int(lines[i][2]) * 0.5
table.append([name, score])
import xlwt
wb = xlwt.Workbook()
st = wb.add_sheet("data")
style = xlwt.XFStyle()
al = xlwt.Alignment()
al.horz = 0x02
al.vert = 0x01
style.alignment = al
style2 = xlwt.easyxf("font:bold on")
style2.alignment = al
title = ["Name", "Score"]
for p in range(len(title)):
st.write(0, p, title[p], style2)
for i in range(len(table)):
for j in range(len(table[i])):
st.write(i+1, j, table[i][j], style)
wb.save("output_path.xls")
完整代码为:
import xlwt
with open('file_path.txt') as f:
f.readline()
lines = f.readlines()
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i] = lines[i][:-1]
lines[i] = lines[i].split('\t')
table = []
for i in range(len(lines)):
name = lines[i][0]
score = int(lines[i][1]) * 0.5 + int(lines[i][2]) * 0.5
table.append([name, score])
wb = xlwt.Workbook()
st = wb.add_sheet("data")
style = xlwt.XFStyle()
al = xlwt.Alignment()
al.horz = 0x02
al.vert = 0x01
style.alignment = al
style2 = xlwt.easyxf("font:bold on")
style2.alignment = al
title = ["Name", "Score"]
for p in range(len(title)):
st.write(0, p, title[p], style2)
for i in range(len(table)):
for j in range(len(table[i])):
st.write(i+1, j, table[i][j], style)
wb.save("output_path.xls")
以下回答来自chatgpt
在Python中可以使用csv模块将数据从txt文件中提取出来并保存为表格数据。具体步骤如下:
with open('file.txt', 'r') as f:
lines = f.readlines()
2, 对读取到的数据进行处理,分离出每个元素,并组织为list of list的形式,例如:
new_lines = []
for line in lines:
new_line = []
elements = line.strip('[]').split(',')
for element in elements:
new_line.append(element.strip('\''))
new_lines.append(new_line)
3, 将数据保存为csv文件,例如:
import csv
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for line in new_lines:
writer.writerow(line)
这样就可以将数据保存为表格形式的csv文件。如果需要使用Excel等表格软件打开,则需要将csv文件后缀名改为.csv。