【发布时间】:2020-08-05 17:23:30
【问题描述】:
一直停留在这个(很可能非常简单)问题上,但我对 Excel 的输出只打印了最终循环中的值。我相信这与缩进有关,并尝试将值排除在失败的 for 循环之外。以下是一些有助于理解问题的虚拟代码:
#dummy code
#reads each file in folder, runs through a bunch of functions, and prints output in console
import os,glob
import csv
import pandas as pd
filename ='path to folder'
for filename in glob.glob(os.path.join(folder_path, '*.txt')):
with open(filename, 'r') as f:
text = f.read()
data =function1(file= filename)
data= function2(file= filename)
data = function3(file= filename)
final =pd.DataFrame(data)
print(final)
final.to_excel('output.xlsx')
控制台中的输出看起来像这样,这是正确的,我想导出到 csv:
0 some text here ...
1 more text...
2 clear text...
3 final data...
0
0 yes no...
1 does lots...
2 happy sunflower ...
3 ate food...
0
0 final data ...
1 apple strawberry...
2 different dataset...
3 dinne meals ...
任何建议将不胜感激。谢谢。
【问题讨论】:
-
pandas.pydata.org/pandas-docs/stable/reference/api/… 具体参见
ExcelWriter can also be used to append to an existing Excel file上的示例。您在循环的每一次传递中都会覆盖'output.csv',因此您只会得到最后覆盖的内容。
标签: python excel pandas for-loop