如何打开并遍历CSV文件列表 - Python

时间:2018-03-16 02:57:51

标签: python csv

我有一个CSV文件的路径名列表。我需要打开每个CSV文件,获取没有标题的数据,然后将它们全部合并到一个新的CSV文件中。

我有这个代码,它为我提供了CSV文件路径名列表:

file_list = []
for folder_name, sub_folders, file_names in os.walk(wd):
    for file_name in file_names:
        file_extention = folder_name + '\\' + file_name
        if file_name.endswith('csv'):
            file_list.append(file_extention)

我的清单的一个例子是:

['C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data1.csv',
 'C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data2.csv',
 'C:\\Users\\Documents\\GPS_data\\West_coast\\Westland\\GPS_data3.csv']

我正在努力弄清楚要做什么,任何帮助都会非常感激。感谢。

1 个答案:

答案 0 :(得分:2)

主要思想是读取文件的每一行,并将其写入新文件。但请记住跳过包含列标题的第一行。我以前推荐使用cvs模块,但是它似乎没有必要,因为这个任务不需要分析数据。

file_list = ['data1.csv','data2.csv']

with open('new.csv', 'w') as newfile:  # create a new file
    for filename in filelist:
        with open(filename) as csvfile:
            next(csvfile)   # skip the header row
            for row in csvfile:
                newfile.write(line) # write to the new csv file

编辑:澄清了我的答案。