conor tighe.
conor tighe.

Reputation: 123

How to write the contents of one CSV file to another

I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original.

IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
    wr = csv.writer(data, quoting=csv.QUOTE_ALL)
    with open(IRIS) as f:
        next(f)
        for line in f:
            wr.writerow(line)

The code above is my most recent attempt, when I try run it I get the following error:

a bytes-like object is required, not 'str'

Upvotes: 1

Views: 3895

Answers (2)

martineau
martineau

Reputation: 123393

It's because you opened the input file with with open(IRIS_data, 'wb'), which opens it in binary mode, and the output file with just with open(IRIS) which opens it in text mode.

In Python 3, you should open both files in text mode and specify newline='' option)—see the examples in the csv module's documentation)

To fix it, change them as follows:

with open(IRIS_data, 'w', newline='') as data:

and

with open(IRIS, newline='') as f:

However there are other issues with you code. Here's how to use those statements to get what I think you want:

import csv

IRIS = "IRIS.csv"
IRIS_data = "IRIS_data.csv"

with open(IRIS, 'r', newline='') as f, open(IRIS_data, 'w', newline='') as data:
    next(f)  # Skip over header in input file.
    writer = csv.writer(data, quoting=csv.QUOTE_ALL)
    writer.writerows(line.split() for line in f)

Contents of IRIS_data.csv file after running the script with your sample input data:

"6.4","2.8","5.6","2.2","2"
"5","2.3","3.3","1","1"
"4.9","2.5","4.5","1.7","2"
"4.9","3.1","1.5","0.1","0"
"5.7","3.8","1.7","0.3","0"
"4.4","3.2","1.3","0.2","0"
"5.4","3.4","1.5","0.4","0"
"6.9","3.1","5.1","2.3","2"
"6.7","3.1","4.4","1.4","1"
"5.1","3.7","1.5","0.4","0"

Upvotes: 1

tupui
tupui

Reputation: 6528

You have to encode the line you are writing like this:

wr.writerow( line.encode(”utf8”))

Also open your file using open(..., ‘wb’). This will open the file in binary mode. So you are certain the file is actually open in binary mode. Indeed it is better to now explicitly the encoding than assuming it. Enforcing encoding for both reading and writing will save you lots of trouble.

Upvotes: 0

Related Questions