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)
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).
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.