Python-将多个文件导入到一个.csv文件 [英] Python- Import Multiple Files to a single .csv file
本文介绍了Python-将多个文件导入到一个.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我的数据文件的样子:
我对python相当陌生,但是我想出了以下代码:
导入glob
结果= glob.glob('./*。data')
fout ='c:/Results/res.csv'
fout = open(res.csv,'w')
用于结果文件:
g = open(file,r)
fout.write(g.read ())
g.close()
fout.close()
上述代码的问题是,所有的数据都被复制到只有两列125 * 21行。
任何帮助非常感谢!
解决方案
import glob
files = [打开(f)for glob.glob('./*。data')]#打开文件列表
fout = open(res.csv ,'w')
用于范围内的行(21):
用于文件中的f:
fou t.write(f.readline()。strip())#strip去掉尾随的换行符
fout.write(',')
fout.write('\\\
')
fout.close()
请注意,如果尝试使用大量数据的文件,我相信在Python中的默认限制是256.
I have 125 data files containing two columns and 21 rows of data and I'd like to import them into a single .csv file (as 125 pairs of columns and only 21 rows). This is what my data files look like:
I am fairly new to python but I have come up with the following code:
import glob
Results = glob.glob('./*.data')
fout='c:/Results/res.csv'
fout=open ("res.csv", 'w')
for file in Results:
g = open( file, "r" )
fout.write(g.read())
g.close()
fout.close()
The problem with the above code is that all the data are copied into only two columns with 125*21 rows.
Any help is very much appreciated!
解决方案
This should work:
import glob
files = [open(f) for f in glob.glob('./*.data')] #Make list of open files
fout = open("res.csv", 'w')
for row in range(21):
for f in files:
fout.write( f.readline().strip() ) # strip removes trailing newline
fout.write(',')
fout.write('\n')
fout.close()
Note that this method will probably fail if you try a large number of files, I believe the default limit in Python is 256.
这篇关于Python-将多个文件导入到一个.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文