import csv
with open(\'thefile.csv\', \'rb\') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
Borrowing from this answer, it seems like the cleanest solution is to use io.TextIOWrapper
. I managed to solve this problem for myself as follows:
from io import TextIOWrapper
...
with open(filename, 'wb') as csvfile, TextIOWrapper(csvfile, encoding='utf-8', newline='') as wrapper:
csvwriter = csv.writer(wrapper)
for data_row in data:
csvwriter.writerow(data_row)
The above answer is not compatible with Python 2. To have compatibility, I suppose one would simply need to wrap all the writing logic in an if
block:
if sys.version_info < (3,):
# Python 2 way of handling CSVs
else:
# The above logic