1

I am writing a simple script with Python3.6 and am using the csv module to create a csv file. My code is attached below, and is a carbon copy of multiple examples I have found online, but when I run the code, I get the error message TypeError: a bytes-like object is required, not a 'str'.

import csv
File_Name = Test.csv
with open(File_Name, 'wb') as csvfile:
   filewriter = csv.writer(csvfile,delimiter=',')
   filewriter = writerow(['Paul','Mary'])
3
  • Use with open(File_Name, 'w') as csvfile Commented Sep 13, 2017 at 20:30
  • 2
    where does writerow come from? You are overriding filewriter Commented Sep 13, 2017 at 20:37
  • In Python 3.x the proper way to open the csv file for writing is open(open(File_Name, 'w', newline='') as csvfile: as shown in the examples in the documentation.. You also need to use filewriter.writerow(['Paul','Mary']). Commented Sep 13, 2017 at 20:41

4 Answers 4

3

The csvwriter instance shouldn't be reassigned to. It should be used to write the rows.

In python 3, you should open the file in write only mode with newline='' per documentation.

import csv

filename = 'Test.csv'

with open(filename, 'w', newline='') as csvfile:
   file_writer = csv.writer(csvfile,delimiter=',')
   file_writer.writerow(['Paul','Mary'])
Sign up to request clarification or add additional context in comments.

Comments

2

If you don't need the binary mode, you can use this :

with open(File_Name, 'w') as csvfile:
   filewriter = csv.writer(csvfile,delimiter=',')
   filewriter.writerow(['Paul','Mary'])

Check the table here to see details about the different modes available.

Comments

2

You have to change from 'wb' to 'w' and file name should be in quotation("Test.csv" or 'Test.csv') see below

import csv
File_Name = "Test.csv"
with open(File_Name, 'w') as csvfile:
    filewriter = csv.writer(csvfile,delimiter=',')
    filewriter.writerow(['Paul','Mary'])

Comments

1

The thing is that you are opened file in a binary mode

with open(File_Name, 'wb') as csvfile:

This means that all data read from the file is returned as bytes objects, not str. If you don't need it, try:

with open(File_Name, 'w') as csvfile:

Also you should use writerow method of the csvwriter instead of reassign it:

file_writer.writerow(['Paul','Mary'])

Comments

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.