【发布时间】:2018-12-26 22:07:22
【问题描述】:
import pandas as pd
import glob
import csv
files=glob.glob('*.csv')
for file in files:
df=pd.read_csv(file)
a=sum(df.iloc[: , 0])
with open ('output.txt','w') as f:
f.write("sum of the first column is "+ str(a))
f.close()
我想为文件夹中的每个输入文件编写输出文件。在输出文件中,我想获得有关每个文件中 1. 列总和的信息。例如。在一个文件夹中,我有文件 [input1,input2,input3],我想为每个输入文件在同一个文件夹中创建文件 [otuput1,output2,output3]。在这段代码中,我只有一个输出文件。
【问题讨论】:
-
旁注:
f.close()不是必需的;您(正确地)使用with块打开文件,因此在执行离开with块的那一刻(即使引发异常),文件会自动关闭;显式的f.close()是多余的。如果您没有使用with块,您只需要显式调用close(例如,因为文件在一个函数调用中打开,然后在另一个函数调用中关闭;这种情况相对较少,首选with块在 99% 的情况下,由于忘记或绕过手动close呼叫的风险)。
标签: python python-3.x pandas