Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV writer blank line

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?

like image 393
Lost1 Avatar asked Sep 11 '17 17:09

Lost1


People also ask

Why does my CSV file have blank lines?

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.

How do I write to a CSV file in Python?

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 .

How to suppress Windows line translation in Python CSV file?

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).

How do I read a CSV file?

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 () ).


2 Answers

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.

like image 145
cuuupid Avatar answered Oct 13 '22 11:10

cuuupid


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")
like image 36
francisco sollima Avatar answered Oct 13 '22 10:10

francisco sollima