I have a CSV file, which has
spam
in it. Then, i did
with open(directory, "a") as config_csv:
writer = csv.writer(config_csv)
writer.writerow(["something"])
writer.writerow(["something else"])
I expected
spam
something
something else
Instead, I got
spam
"something"
"something else"
How do I get the thing I want?
Writing CSV adds blank lines between rows. The way Python handles newlines on Windows can result in blank lines appearing between rows when using csv.writer. In Python 2, opening the file in binary mode disables universal newlines and the data is written properly.
In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes into the file directly. If you don't open the file in binary mode, it will write because on Windows text mode will translate each into .
In Python 3 the required syntax changed and the csv module now works with text mode 'w', but also needs the newline="" (empty string) parameter to suppress Windows line translation (see documentation links below).
The simplest example of reading a CSV file: Reading a file with an alternate format: The corresponding simplest possible writing example is: Since open () is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding () ).
With the CSV module, use delimiter
, quotechar
, and quoting=csv.QUOTE_MINIMAL
options to desired effect:
import csv
with open(file, "a", newline='') as config_csv:
writer = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(["something"])
writer.writerow(["something else"])
file
will then contain:
spam
something
something else
Tested on Python 3.4.
If what you need is just what you said, there's not need for the module csv
:
with open(directory, "a") as config_csv:
config_csv.write("something\n")
config_csv.write("something else\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