【问题标题】:How to save python result as excel xlsx如何将python结果保存为excel xlsx
【发布时间】:2022-01-21 01:39:08
【问题描述】:

以下代码读取.txt文件并打印结果,但我需要将结果另存为.xlsx,我搜索了互联网但没有得到任何解决方案,有人可以帮助我吗?

import os

path = input('Enter Directory:')

os.chdir(path)


def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())

for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
        read_text_file(file_path)

.txt 文件中的数据格式如下:

"174125_1.jpg" 
"174127_1.jpg" 
"174128_1.jpg" 
"174129_1.jpg" 
"174130_1.jpg" 
"176475_1.jpg" 
"178836_1.jpg" 
"179026_1.jpg" 
"179026_2.jpg" 
"179026_3.jpg" 
"179026_4.jpg" 
"179026_5.jpg" 

它们是来自上传到电子商务的图像的注册数据。

【问题讨论】:

  • 嗨,如果您发现其中一个答案有帮助,请接受并投票结束此问题。

标签: python excel txt


【解决方案1】:

看看this 库。它允许您在 python 中创建 excel 文件。 编辑:您的示例非常简单:

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        i = 0
        for line in f:
           # Write to xlsx using row, column syntax
           worksheet.write(i, 0, line)
           i += 1

【讨论】:

    【解决方案2】:

    您可以为此使用熊猫。使用 excel 非常方便,因为您可以在 pandas 中构建列和行,然后将它们导出到 excel。

    这是一个如何将 Pandas 数据框存储到 Excel 的示例。

    df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
    df1.to_excel("output.xlsx") 
    

    编辑:

    现在我知道了,我可以自信地说,pandas 是你想要使用的库。

    使用 pandas,您的整个代码可以减少到 3 行:

    import pandas as pd
    
    df = pd.read_csv('input.txt', names=["pictures"])
    df.to_excel('output.xlsx')
    

    如果您打算将 python 用于数据驱动的任务。 Pandas 是此类内容的最佳库,我强烈建议您学习它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多