我将csv文件分散在多个目录中,每个csv文件只有一列包含数据。我想要做的是读取所有这些文件,并将每个文件的列放入csv文件中。最终的csv文件将具有文件名作为其标题的列和来自其原始文件的相应数据作为其列数据。将CSV文件数据合并到一个CSV文件中
这里面~/csv_files/ ls
ab arc bat-smg bn cdo crh diq es fo gd haw ia iu ki ksh lez lv mo na no os pih rmy sah simple ss tet tr ur war zea
ace arz bcl bo ce cs dsb et fr gl he id ja kk ku lg map-bms mr nah nov pa pl rn sc sk st tg ts uz wo zh
af as
每个目录有两个CSV文件,我的目录结构,我想用os.walk()函数,但我觉得我的os.walk的理解不正确,这就是为什么目前我所拥有的东西不会产生任何东西。
import sys, os
import csv
root_path = os.path.expanduser(
'~/data/missing_files')
def combine_csv_files(path):
for root, dirs, files in os.walk(path):
for dir in dirs:
for name in files:
if name.endswith(".csv"):
csv_path = os.path.expanduser(root_path + name)
if os.path.exists(csv_path):
try:
with open(csv_path, 'rb') as f:
t = f.read().splitlines()
print t
except IOError, e:
print e
def main():
combine_csv_files(root_path)
if __name__=="__main__":
main()
我的问题是:
- 什么我错在这里做什么?
- 我可以从另一个文件中读取一个csv列,并将该数据作为列添加到另一个文件中,因为csv文件更依赖于行,这里行之间没有依赖关系。
最后我想获得这样的csv文件,(这里有潜在的头)
ab_csv_data_file1, ab_csv_data_file2, arc_csv_data_file1, arc_csv_data_file2
加上'打印csv_path'到最里面的'for'循环,以确保路径是你所期望的 – bernie
你滥用os.walk() – Sheng
圣洁嵌套蝙蝠侠。 – squiguy