Reputation: 53
I'm copying the contents of a csv file and writing these to another so I can modify it later but can't figure out what the simple solution is. I thought I could keep the input csv_file
and output writer
files open while copying the contents, don't know if that's a good idea. My code
import csv, os
file_path = 'path/to/file.csv'
output_path = os.path.dirname(os.path.abspath(file_path)) + '/'
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
with open(output_path + 'results.csv', 'w', newline='') as writer:
for line in data_source:
writer.writerow(line)
This is the error I get:
AttributeError: '_io.TextIOWrapper' object has no attribute 'writerow'
Upvotes: 0
Views: 973
Reputation: 2329
The object that you think is the writer is not. Instead, you should construct the writer separately.
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
with open(output_path + 'results.csv', 'w', newline='') as results_file:
data_sink = csv.writer(results_file) #This is the important line
for line in data_source:
data_sink.writerow(line)
Upvotes: 3
Reputation: 1498
Can you try this code and see if this works?
import csv, os
file_path = 'path/to/file.csv'
output_path = os.path.dirname(os.path.abspath(file_path)) + '/'
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
f = open(output_path + 'results.csv', 'w', newline='')
with f:
writer = csv.writer(f)
for line in data_source:
writer.writerow(line)
Upvotes: 1
Reputation: 336
The error means that there is no method for writerow for the writer.
Upvotes: -1