下面的代码读取 .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"
它们是来自上传到电子商务的图像的注册数据。
最佳答案
您可以为此使用 Pandas 。这对于 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 是此类内容的最佳库,我强烈建议您学习它。
关于python - 如何将python结果保存为excel xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70404851/