I have folder with hundreds of csv files, with one row in every file containing country names. I would like to loop through all the files, select the lines with country name "FIN" and create new csv files from the selected lines.
This is how far I have gotten:
import csv
import glob
for filename in glob.glob('\directory\*.csv'):
with open(filename, 'r') as i, open('\directory_for_new_files\fin_{}'.format(filename), 'w') as o:
r = csv.reader(i, delimiter=',')
w = csv.writer(o, delimiter=',')
for row in r:
if 'FIN' in row[3] or 'flag' in row[3] :
w.writerow(row)
The "fin_{}'.format(filename)"
part seems to be the problem, since when I replace it with just a name (like 'testfile.csv') the script works, but of course with the problem that it constantly overwrites the same file. So how do I get the script to create a new output file for every input file?
Error message:
with open(r'D:\Koko Suomen ihmispaineet\Ihmispaineet_26_10_2018\Global fishing watch\fishing_effort\daily_csvs_finland\fin_{}'.format(filename), 'w') as o:
IOError: [Errno 22] invalid mode ('w') or filename: 'D:\Koko Suomen ihmispaineet\Ihmispaineet_26_10_2018\Global fishing watch\fishing_effort\daily_csvs_finland\fin_D:\Koko Suomen ihmispaineet\Ihmispaineet_26_10_2018\Global fishing watch\fishing_effort\daily_csvs\2012-01-01.csv'