1

I'm a extremely beginner in Python and all I want to do is to delete space in some sells in the table. But because of the error, I cannot write csv. I've already checked several related posts in stackoverflow, but still couldn't correct my cord.

Error

line 27, in
csvWriter.writerow(corrected)
TypeError: 'str' does not support the buffer interface

Code

import csv

# Read CSV
csvfile = '/Users/Study/Data/WGI/forPython.csv'
f = open(csvfile, 'r', newline='')
data = csv.reader(f)

# 
g = open('/Users/Study/Data/WGI/WGI_Data_Renamed_Python.csv', 'ab')
csvWriter = csv.writer(g)

# 
corrected = []

count = 0

# 
for row in data:
    corrected.append([])             
    corrected[count] = str.rstrip(row[0])
    count = count + 1

print(corrected)

# 
csvWriter.writerow(corrected)
g.close()

1 Answer 1

2

Apparently, csv.writer in Python 3 doesn't support binary output streams. This isn't mentioned in the documentation, and worse, it's backwards from the Python 2 recommendation of always opening the underlying files with b.

Luckily for you, the fix is easy: just open the file in text mode instead of binary. The docs also recommend that you specify newline='' when opening the file, so you might as well do that too.

g = open('/Users/Study/Data/WGI/WGI_Data_Renamed_Python.csv', 'a', newline='')
csvWriter = csv.writer(g)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your post, Henry! But I still got the same error even if I modified the line you've mentioned.
@user51966 Python 3 seems to have silently dropped support for binary output streams in the csv writers. I'd updated my answer accordingly; take a look and see if it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.