Python CSV writer blank line
Asked Answered
T

3

9

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?

Turbulence answered 11/9, 2017 at 17:31 Comment(0)
V
2

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")
Venal answered 11/9, 2017 at 17:34 Comment(0)
T
5

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.

Terry answered 11/9, 2017 at 17:39 Comment(2)
how does csv.QUOTE_NONE and csv.QUOTE_MINIMAL differ?Turbulence
csv.QUOTE_MINIMAL quotes fields that have delimiters or quotechar. (From the docs: Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.) csv.QUOTE_NONE quotes no fields.Terry
V
2

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")
Venal answered 11/9, 2017 at 17:34 Comment(0)
G
2

Other answers in SE did not work for me. What I did was:

with open('ADC.csv', 'a') as csvfile:
    csv_Writer = csv.writer(csvfile, delimiter=';', lineterminator='\n')
Gratitude answered 8/9, 2020 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.