Python write a new csv file by filtering selected rows from an existing csv file

后端 未结 3 1218
刺人心
刺人心 2021-01-29 02:40

just a question, I was trying to write selected rows from a .csv file to a new .csv file, but there is an error.

The test.csv file that I was trying to read is like this

3条回答
  •  臣服心动
    2021-01-29 03:05

    Since you are using the csv module anyway, why not write the file as you are reading it in:

    import csv
    
    with open('in.csv', 'r') as i, open('out.csv', 'w') as o:
       r = csv.reader(i, delimiter='\t')
       w = csv.writer(o, delimiter='\t')
       for row in r:
          if row[0].split('-')[0] == '2014':
              w.write(row)
    

提交回复
热议问题