Notsoprosql
Notsoprosql

Reputation: 199

Python TypeError attempting to writerow back to CSV file

I am trying to open some data from a CSV edit it and then put it back in the row at column number 12. The edit work (the re.sub element is working correctly) But I am having troubles writing it back into the new 3.csv. Any Advice on how I can do this please? I also belive I need to close the files?

The error I am getting is: TypeError: a bytes-like object is required, not 'str'

import csv
import re

with open('2.csv', "r") as inFile, open("3.csv", "wb") as outFile:
    reader = csv.reader(inFile)
    writer = csv.writer(outFile)
    for row in reader:
        newText = re.sub(r'.*SC', r'SC', row[4])
        writer.writerow(newText)

Here is the data I am trying to modify to help understand the code above.

Header 1,Header 2,Header 3,Header 4,Header 5 
1,2,3,4,DESCRIPTION
1,2,3,4,DEffffSCRIPTION
1,2,3,4,aaaaDESCRIPTION
1,2,3,4,<>DESCRIPTION

Here is what I am trying to achieve:

Header 1,Header 2,Header 3,Header 4,Header 5 
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION

Upvotes: 0

Views: 58

Answers (2)

dspencer
dspencer

Reputation: 4461

You don't need to open the 3.csv file in bytes mode, so may use "w" instead of "wb" as the mode for "3.csv". According to the documentation, CSV files should be opened using newline='' to ensure that newlines are interpreted correctly.

with open('2.csv', "r") as inFile, open("3.csv", "wb") as outFile:

should therefore be

with open('2.csv', "r", newline="") as inFile, open("3.csv", "w", newline="") as outFile

When opening a file in bytes mode, you may only write bytes to that file. You would therefore need to encode your strings first.

You don't need to explicitly close either file, as you are using the with statement, meaning that the context manager will take care of this.

Upvotes: 1

Mark Tolonen
Mark Tolonen

Reputation: 177406

From the error message I assume Python 3. Per csv documentation, open files as:

with open('2.csv','r',newline='') as inFile, open("3.csv",'w',newline='') as outFile:

Also newText is just a single string. To write the file correctly, replace row[4] with the substitution, and write the whole row.

import csv
import re

with open('2.csv','r',newline='') as inFile, open('3.csv','w',newline='') as outFile:
    reader = csv.reader(inFile)
    writer = csv.writer(outFile)
    for row in reader:
        row[4] = re.sub(r'.*SC', r'SC', row[4])
        writer.writerow(row)

Upvotes: 2

Related Questions