Reputation: 99
I have a simple pythono code that parses json file and returns it as dictionary. I have to write this in to CSV file but only with the LF as a line terminator. However, Carriage return appears anyway even using newline=''. wb mode is not an option as i receive this error
return self.writer.writerow(self._dict_to_list(rowdict)) TypeError: a bytes-like object is required, not 'str'
My code for CSV writing:
with open(statsFilePath,'w+', newline='', encoding='utf8') as f:
writer = csv.DictWriter(f, header , delimiter = '|')
for row in result:
writer.writerow(row)
And here is the screenshot of what i see in Notepad++
UPDATE, SOLVED
The DictWriter used the default line terminator. Changing the code to this, solved the issue:
with open(statsFilePath,'w+', newline='', encoding='utf8') as f:
writer = csv.DictWriter(f, header , delimiter = '|', lineterminator="\n")
for row in result:
writer.writerow(row)
Upvotes: 1
Views: 1529
Reputation: 2479
The csv Dialect
decides which line terminator to use and by default it is \r\n
.
You need to specify lineterminator
when defining the writer:
writer = csv.DictWriter(f, header , delimiter = '|', lineterminator='\n')
Upvotes: 2
Reputation: 181390
Try this:
with open(statsFilePath,'w+', newline='\n', encoding='utf8') as f:
Please remember that LF
is probably not what you are looking for. You are looking for CR
as your line separator (UNIX's default).
Upvotes: 1