I would like to create a code which is Python 2.7-3.6 compatible I am trying to fix a problem with the csv module where initially I used outfile=open('./test.csv','wb')
in Python 2.7 now I have to use outfile=open('./test.csv','w')
like in this question otherwise I will incur in a
TypeError: a bytes-like object is required, not 'str'
.
A the moment I am fixing it using this code:
import sys
w = 'w'
if sys.version_info[0] < 3:
w = 'wb'
# Where needed
outfile=open('./test.csv',w)
Not very nice, is there any better solution for opening the file in 'wb' if I am using Python 2.7 and in w
if I am using Python 3.x? To clarify I have to use wb
in Python 2.7 because otherwise, I'll have a blank line every time I add a new line to a file.
When opening files to be used with module
csv
on python 3 you always should addnewline=""
the the open statement:The
newline
parameter does not exist in python 2 - but if you skip it in python 3 you get misshaped csv output on windows with additional empty lines in it.See csv.writer (python 3):
You should use a contextmanaging
with
as well:to get your filehandles closed even if you run into some kind of exception. This is python 2 safe - see Methods of file objects:
Your solution - ugly but works:
The problem is the parameter
newline
does not exist in python 2. To fix that you would have to wrap/monkypathopen(..)
including the contextmanaging.