Reputation: 101
I have written the program but it apparently does not work. I mean that last part of the code. The program is creating the file and adding some stuff to csv file. The last part of the code should add some more data to the already existing file but every time I want to run this program I have got this kind of error:
Traceback (most recent call last):
File "/Users/grzegorzspytek/Desktop/Sending_automated_mails/nw_csv.py", line 121, in <module>
for row in reader:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 111, in __next__
self.fieldnames
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 98, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
After that, I changed "open mode" from "rb" to "r+"
Traceback (most recent call last):
File "/Users/grzegorzspytek/Desktop/Sending_automated_mails/nw_csv.py", line 125, in <module>
"Email": row["Email"]
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tempfile.py", line 481, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
It looks like I was asked to change it back, but every time I do that the errors occur alternately. Any solution for that?
Here is the code of my program:
import csv
import shutil
import os
from tempfile import NamedTemporaryFile
def get_len(path):
with open(path, "r") as csvfile:
reader = csv.reader(csvfile)
read_list = list(reader)
return len(read_list)
#check if this is the file,
def append_data(path, name, email):
if not os.path.isfile(path):
with open(path, "w") as csvfile:
fieldnames = ["ID", "Name", "Email"]
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writeheader()
print("Creating file...")
with open(path, "a") as csvfile:
fieldnames = ["ID", "Name", "Email"]
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writerow({
"ID": get_len(path),
"Name": name,
"Email": email
})
print("Adding data for " + name)
path = "/Users/grzegorzspytek/Desktop/Sending_automated_mails/data.csv"
append_data(path, "grzesiek", "grz.spy")
filename = "data.csv"
temp_file = NamedTemporaryFile(delete=False)
with open("data.csv", "rb") as csvfile, temp_file:
reader = csv.DictReader(csvfile)
fieldnames = ["ID", "Name", "Email"]
writer = csv.DictWriter(temp_file, fieldnames = fieldnames)
for row in reader:
writer.writerow({
"ID": row["ID"],
"Name": row["Name"],
"Email": row["Email"]
})
Upvotes: 1
Views: 86
Reputation: 107015
You should open your temporary file in text mode instead:
temp_file = NamedTemporaryFile(mode='w+', delete=False)
Otherwise the temporary file is opened in binary mode by default as documented.
Upvotes: 1