Python在将内容打印到CSV文件时会跳过换行。

4
我正在尝试创建 .csv 文件。 由于某些原因,在打印条目之前会跳过一行。 以下是输出结果。

enter image description here

但这就是我需要的。

enter image description here

下面是代码。显然,if line != "": 不起作用。
import csv

#-----------------------------------
def csv_writer(data,path):
    """
    Write data to a CSV file path
    """
    with open(path, "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            if line != "":
                writer.writerow(line)

#-----------------------------------
if __name__ == "__main__":
    data = ["first_name,last_name,city".split(","),
            "Tyrese,Hirthe,Strackeport".split(","),
            "Jules,Dicki,Lake Nickolasville".split(","),
            "Dedric,Medhurst,Stiedemannberg".split(",")
            ]
    path = "output.csv"
    csv_writer(data,path)
2个回答

6

有些Python版本(在Windows上)会遇到一个问题:with open(path, "w") as csv_file: 会出现一个假回车符号,导致每行之后都会产生一个空行。

你需要按照文档中所述添加 newline=""。Python 3:

with open(path, "w",newline="") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')

关于 Python 2:
with open(path, "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')

参见:

(请注意,最新的Windows Python版本不再需要此操作,但文档仍然说明)


该问题特定于Windows,并在文档中有所涉及。 - Aaron

2

当您打开文件时,需要使用一个空字符串作为关键字参数newline。这将防止在行之间添加换行符。您的函数应该是:

def csv_writer(data,path):
    """
    Write data to a CSV file path
    """
    with open(path, "w", newline = '') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            if line:
                writer.writerow(line)

请注意,这只是在Windows系统上出现的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接