【发布时间】:2022-06-07 17:15:01
【问题描述】:
例如,如果我有 3 个如下所示的 txt 文件:
文件 1.txt:
a 10
b 20
c 30
文件2.txt:
d 40
e 50
f 60
文件 3.txt:
g 70
h 80
i 90
我想从文件中读取这些数据并创建一个如下所示的 Excel 文件:
特别是在我的情况下,我使用 glob 和循环读取了 100 多个 txt 文件。
谢谢
【问题讨论】:
例如,如果我有 3 个如下所示的 txt 文件:
文件 1.txt:
a 10
b 20
c 30
文件2.txt:
d 40
e 50
f 60
文件 3.txt:
g 70
h 80
i 90
我想从文件中读取这些数据并创建一个如下所示的 Excel 文件:
特别是在我的情况下,我使用 glob 和循环读取了 100 多个 txt 文件。
谢谢
【问题讨论】:
获得所需的输出涉及一些逻辑。
首先,将输入文件处理成单独的列表。您可能需要根据文件的实际内容调整此逻辑。您需要能够获取文件的列。对于提供的示例,我的逻辑有效。
我添加了一个安全检查以查看输入文件是否具有相同的行数。如果他们不这样做,它会严重弄乱生成的 excel 文件。如果发生长度不匹配,您需要添加一些逻辑。
对于写入 excel 文件,将 pandas 与 openpyxl 结合使用非常容易。可能有更优雅的解决方案,但我会把它留给你。
我在代码中引用了一些 SO 答案以供进一步阅读。
要求.txt
pandas
openpyxl
主文件
# we use pandas for easy saving as XSLX
import pandas as pd
filelist = ["file01.txt", "file02.txt", "file03.txt"]
def load_file(filename: str) -> list:
result = []
with open(filename) as infile:
# the split below is OS agnostic and removes EOL characters
for line in infile.read().splitlines():
# the split below splits on space character by default
result.append(line.split())
return result
loaded_files = []
for filename in filelist:
loaded_files.append(load_file(filename))
# you will want to check if the files have the same number of rows
# it will break stuff if they don't, you could fix it by appending empty rows
# stolen from:
# https://stackoverflow.com/a/10825126/9267296
len_first = len(loaded_files[0]) if loaded_files else None
if not all(len(i) == len_first for i in loaded_files):
print("length mismatch")
exit(419)
# generate empty list of lists so we don't get index error below
# stolen from:
# https://stackoverflow.com/a/33990699/9267296
result = [ [] for _ in range(len(loaded_files[0])) ]
for f in loaded_files:
for index, row in enumerate(f):
result[index].extend(row)
result[index].append('')
# trim the last empty column
result = [line[:-1] for line in result]
# write as excel file
# stolen from:
# https://stackoverflow.com/a/55511313/9267296
# note that there are some other options on this SO question, but this one
# is easily readable
df = pd.DataFrame(result)
writer = pd.ExcelWriter("output.xlsx")
df.to_excel(writer, sheet_name="sheet_name_goes_here", index=False)
writer.save()
【讨论】: