Reputation: 45
The problem is how do you read text from one CSV file, identify a certain keyword in the file, read the rows with the keyword, and write those rows to another file. While this problem seems straightforward logically, syntactically it has proven challenging.
The code below is the code I have tried. Interestingly, the print(row) line is able to print exactly the information I am trying to write to the second CSV file. However, I have been unable to accomplish the same task with the CSV write module (https://docs.python.org/3.3/library/csv.html).
import csv
csvfile = open('read_file.csv', 'r')
read = csv.reader(csvfile)
for row in csvfile:
if str('key_word') in row:
#print(row)
with open('write_file.csv', "w") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(row)
The code runs successfully. However, output appears random and disorganized. In essence, there appears to be problems iterating over the CSV file and writing the rows in an organized row-by-row manner.
Upvotes: 1
Views: 4311
Reputation: 45
Here is the answer:
with open('read_file.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
#skip first line
#next(csv_reader)
with open ('write_file.csv', 'w') as new_file:
csv_writer = csv.writer(new_file, delimiter=',')
for line in csv_reader:
if str('keyword') in line:
#print(line[2])
csv_writer.writerow(line)
Upvotes: 0
Reputation: 2022
You don't need to use csv
module at all
csvfile = open('read_file.csv', 'r')
with open('write_file.csv', 'w+') as csv_file2:
for row in csvfile:
if str('key_word') in row:
csv_file2.write(row)
Upvotes: 1
Reputation: 1227
Open both files in different vars before iterating. Don't open the target file every loop iteration. Also don't use for row in csvfile
, use for row in reader
import csv
csvfile = open('read_file.csv', 'r')
reader = csv.reader(csvfile)
with open('write_file.csv', "w+") as csv_file1: # different variable
writer = csv.writer(csv_file1, delimiter=',')
for row in reader:
if str('key_word') in row:
# print(row)
writer.writerow(row)
Upvotes: 4