【问题标题】:How do I extract data from multiple text files to Excel using Python? (One file's data per sheet)如何使用 Python 从多个文本文件中提取数据到 Excel? (每张纸一个文件的数据)
【发布时间】:2018-07-24 03:07:18
【问题描述】:

到目前为止,我的代码可以从文本文件中读取并导出到 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

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

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

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

【问题讨论】:

  • 我推荐pandas.read_csv(...).to_excel(...)
  • 您的 globbing 似乎没有按预期工作。除此之外,这看起来不像是编写 Excel 文件的正确方法。

标签: python excel openpyxl


【解决方案1】:

如果您不反对将输出的 excel 文件作为 .xlsx 而不是 .xls,我建议您使用Pandas 的一些功能。特别是pandas.read_csv()DataFrame.to_excel()

我提供了一个完全可重复的示例,说明您可以如何进行此操作。请注意,我在前 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()

输出示例:

【讨论】:

  • 谢谢! :) 因为我有三个文件我想从中提取信息,我会使用 df = ('file1.txt', 'file2.txt', 'file3.txt') 之类的东西而不是你放的三行吗?希望这不是一个愚蠢的问题!
  • 没有必要这样做。如果删除这 3 行并从包含要转换为一个 excel 文件的 .txt 文件的目录中运行脚本,它应该可以正常工作。或者,如果您想从不同的目录运行 python 脚本,您可以使用 os 模块来更改目录 - os.chdir(r"c:\some\folder")。无论您选择做什么,打印两个列表(txt_list 和 sheet_list)可能会有所帮助,以说服自己这是如何工作的。
  • 我很确定它在读取其中一个 .txt 文件时遇到了问题。看起来它可能与分隔符有关。这个答案 - stackoverflow.com/questions/18039057/… 有一些关于与此错误相关的一些解决方案的好信息。希望对您有所帮助。
  • FWIW 通过 Pandas 从 CSV 到 XLSX 效率低下,因为这意味着从行到列再回到行。 openpyxl 和 xlsxwriter 都支持流式传输,直接使用它们更有意义,尤其是在文件很大的情况下。
  • @Ruth - 这可能是读取目录中一个或多个 .txt 文件的问题。这可能与使用的分隔符有关。或许可以使用 pandas.read_csv() 探索一些可选参数。
猜你喜欢
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2017-02-12
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多