extract rows and filenames from multiple csv files

后端 未结 5 407
醉酒成梦
醉酒成梦 2021-01-17 02:28

I have multiple csv files with date as filename (20080101.csv to 20111031.csv) in a folder. The csv files have common headers. The csv file looks like this:



        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 02:41

    The following should work:

    import csv
    with open('output.csv', 'w') as outfile:
        outfile.write('X ; Y ; Z ; filename\n')
        fmt = '1 ; 2 ; %s ; %s\n'
        files = ['20080101.csv', '20080102.csv', '20080103.csv', '20080104.csv']
        for file in files:
            with open(file) as f:
                reader = csv.reader(f, delimiter=';')
                for row in reader:
                    if len(row) > 2 and row[0].strip() == '1' and row[1].strip() == '2':
                        outfile.write(fmt % (row[2].strip(), file[:-4]))
                        break
                else:
                    outfile.write(fmt % ('NA', file[:-4]))
    

提交回复
热议问题