python - Write from Text files to CSV Files -
i trying write rows contain string: bunch of text files. code:
import os import glob import csv import re #defining keyword keyword = '2012-07-02' #code merge relevant log files 1 file , insert open('combined-01022012.txt' , 'w', newline = '') combined_file: csv_output = csv.writer(combined_file) filename in glob.glob('fao_agg_2012_part_*.txt'): open(filename, 'rt', newline = '') f_input: #with gzip.open((filename.split('.')[0]) + '.gz', 'rt', newline='') f_input: csv_input = csv.reader(f_input) row in csv_input: row.insert(0, os.path.basename(filename)) try: if keyword in row[2]: csv_output.writerow(row) #row.insert(0, os.path.basename(filename)) #csv_output.writerow(row) except: continue continue
everything seems right , code runs nothing gets written on text file. going wrong?
your main problem in lines:
row.insert(0, os.path.basename(filename)) try: if keyword in row[0]: csv_output.writerow(row) except: continue
you're inserting parent folder name of current file first entry of row, , on next line you're checking if entry (row[0]
) contains keyword
. unless parent folder contains keyword
(2012-07-02
) condition never evaluate true
. i'd mix as:
if keyword in row[0]: csv_output.writerow([os.path.basename(filename)] + row)
also, using blank except
very, bad idea. if you're looking capture specific exception, define in except
clause.
Comments
Post a Comment