I realize that the csv library in Python always generates DOS end-of-line characters. Even if I use the 'wb'
mode, even if I use Linux.
import csv f = open('output.txt', 'wb'); writer = csv.writer(f) writer.writerow([2,3,4]); f.close()
The above code always uses '\r\n'
as the end of line separator. How can I make it use use '\n'
only?
This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object created with open() function and with write permission as a parameter. Every row written in the file issues a newline character by default.
Python's file objects, by default, use universal newlines when reading files. That means that any of '\n' , '\r' and '\r\n' strings are translated into '\n' when you read a file.
Close a CSV FileIt's a good practice to close the file once you are finished with it. You don't want an open file running around taking up resources! Use the close() function to close an open file.
You can give your writer
instance a custom lineterminator
argument in the constructor:
writer = csv.writer(f, lineterminator="\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With