Python CSV编写器空白行

Los*_*st1 6 python csv python-3.x export-to-csv

我有一个 CSV 文件,其中有

spam
Run Code Online (Sandbox Code Playgroud)

在里面。然后,我做到了

 with open(directory, "a") as config_csv:
    writer = csv.writer(config_csv)
    writer.writerow(["something"])
    writer.writerow(["something else"])
Run Code Online (Sandbox Code Playgroud)

我期望

spam
something
something else
Run Code Online (Sandbox Code Playgroud)

相反,我得到了

spam

"something"

"something else"
Run Code Online (Sandbox Code Playgroud)

我如何得到我想要的东西?

小智 5

对于 CSV 模块,使用delimiterquotecharquoting=csv.QUOTE_MINIMAL选项达到所需效果:

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"])
Run Code Online (Sandbox Code Playgroud)

file然后将包含:

spam
something
something else
Run Code Online (Sandbox Code Playgroud)

在 Python 3.4 上测试。


fra*_*ima 2

如果您所需要的正是您所说的,则不需要该模块csv

with open(directory, "a") as config_csv:
    config_csv.write("something\n")
    config_csv.write("something else\n")
Run Code Online (Sandbox Code Playgroud)