如何使用 Python 将多个文本文件中的数据提取到 Excel 中? (每张纸一个文件的数据)

2024-06-19

到目前为止,为了让我的代码读取文本文件并导出到 Excel,我有:

import glob

data = {}
for infile in glob.glob("*.txt"):
    with open(infile) as inf:
        data[infile] = [l[:-1] for l in inf] 

with open("summary.xls", "w") as outf:
    outf.write("\t".join(data.keys()) + "\n")
    for sublst in zip(*data.values()):
        outf.write("\t".join(sublst) + "\n")

这样做的目标是访问特定文件夹中的所有文本文件。

但是,当我运行它时,Excel 给出了一个错误:

“无法打开文件,因为:在文档顶层无效。第 1 行,位置 1。outputgooderr.txt outputbaderr.txt。fixed_inv.txt

Note:outputgooderr.txt、outputbaderr.txt.、fixed_inv.txt 是我希望导出到Excel 的文本文件的名称,每张纸一个文件。

当我只有一个文件供程序读取时,它就能够提取数据。不幸的是,这不是我想要的,因为我有多个文件。

请让我知道我可以解决这个问题的任何方法。一般来说,我是编程的初学者,非常感谢任何建议!谢谢。


如果您不反对将输出的 Excel 文件作为 .xlsx 而不是 .xls,我建议您使用Pandas https://pandas.pydata.org/pandas-docs/stable/。尤其pandas.read_csv() https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html and DataFrame.to_excel() https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html

我提供了一个完全可重现的示例,说明您可以如何执行此操作。请注意,我在前 3 行中创建了 2 个 .txt 文件用于测试。

import pandas as pd
import numpy as np
import glob

# Creating a dataframe and saving as test_1.txt/test_2.txt in current directory
# feel free to remove the next 3 lines if yo want to test in your directory
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
df.to_csv('test_1.txt', index=False)
df.to_csv('test_2.txt', index=False)

txt_list = [] # empty list
sheet_list = [] # empty list

# a for loop through filenames matching a specified pattern (.txt) in the current directory
for infile in glob.glob("*.txt"): 
    outfile = infile.replace('.txt', '') #removing '.txt' for excel sheet names
    sheet_list.append(outfile) #appending for excel sheet name to sheet_list
    txt_list.append(infile) #appending for '...txt' to txtt_list

writer = pd.ExcelWriter('summary.xlsx', engine='xlsxwriter')

# a for loop through all elements in txt_list
for i in range(0, len(txt_list)):
    df = pd.read_csv('%s' % (txt_list[i])) #reading element from txt_list at index = i 
    df.to_excel(writer, sheet_name='%s' % (sheet_list[i]), index=False) #reading element from sheet_list at index = i 

writer.save()

输出示例:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Python 将多个文本文件中的数据提取到 Excel 中? (每张纸一个文件的数据) 的相关文章

随机推荐