iT邦幫忙

0

Python 获取 txt 文件中的列表,再写入到 Excel 中

我有一个 a.txt 文件,里面存放了一些列表:

[1,2,3,4,5]
[2,5,3,5,3]
[4,3,2,4,2]

我现在想通过 Python 从这个 txt 文件中获取列表的内容,并将它写入到 Excel 中。

我通过 for 循环获取到了 txt 的每一行内容:

file = open("a.txt")
for l in file:
    line = l.strip("\n")
    print(line)

然后,我想使用 xlwt 将每一行的内容写入到 Excel 中,我应该如何写 for 循环,才能遍历每行列表中的内容,将列表中的每一个值都写入到 Excel 中的不同的单元格?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
froce
iT邦大師 1 級 ‧ 2020-06-30 16:40:05
最佳解答
import xlwt

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

with open("test.txt", "r") as f:
    for index, line in enumerate(f.readlines()):
        lineList = line.replace("[", "").replace("]", "").replace("\n", "").split(",")
        for col, item in enumerate(lineList):
            ws.write(index, col, item)

wb.save("test.xls")

我要發表回答

立即登入回答