python - Create subset of large CSV file and write to new CSV file -


i create subset of large csv file using rows have 4th column ass "dot" , output new file.

this code have:

import csv outfile = open('dot.csv','w') open('service_requests_2015_-_present.csv', newline='', encoding='utf-8') f:     reader = csv.reader(f)     row in reader:         if row[3] == "dot":             outfile.write(row) outfile.close() 

the error is:

  outfile.write(row) typeerror: must str, not list 

how can manipulate row able straight write(row), if not, easiest way?

you can combine 2 open statements, statement accepts multiple arguments, this:

import csv  infile = 'service_requests_2015_-_present.csv' outfile = 'dot.csv'  open(infile, encoding='utf-8') f, open(outfile, 'w') o:     reader = csv.reader(f)     writer = csv.writer(o, delimiter=',') # adjust necessary     row in reader:        if row[3] == "dot":            writer.writerow(row)  # no need close statements print('done') 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -