下面的代码读取.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"
它们是从上传到电子商务的图像中获取的注册数据。
发布于 2021-12-18 16:03:43
请看一下这库。它允许您在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
发布于 2021-12-18 16:10:04
你可以用熊猫来做这个。excel非常方便,因为您可以在熊猫中构建列和行,然后将它们导出到excel。
下面是如何将Pandas Dataframe存储到Excel的示例。
df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
index=['row 1', 'row 2'],
columns=['col 1', 'col 2'])
df1.to_excel("output.xlsx")
编辑:
现在我知道了,你想做的事,我可以自信地说,熊猫是你想要使用的图书馆。
使用熊猫,你的整个代码可以减少到3行:
import pandas as pd
df = pd.read_csv('input.txt', names=["pictures"])
df.to_excel('output.xlsx')
此外,如果您打算使用python来执行数据驱动的任务。熊猫是这种东西最好的图书馆,我强烈建议你学习它。
https://stackoverflow.com/questions/70404851
复制相似问题