jim
jim

Reputation: 53

Copy csv values to another csv

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

Answers (3)

code11
code11

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

Cute Panda
Cute Panda

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

lizardcoder
lizardcoder

Reputation: 336

The error means that there is no method for writerow for the writer.

Upvotes: -1

Related Questions