【问题标题】:Python skips line when printing to CSV打印到 CSV 时 Python 会跳行
【发布时间】:2018-02-13 21:31:45
【问题描述】:

我正在尝试创建 .csv 文件。

由于某种原因,它会在打印条目之前跳过行。

这是输出

但这是我需要的

下面是代码。显然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)

【问题讨论】:

    标签: python csv


    【解决方案1】:

    某些 python 版本(在 Windows 上)与 with open(path, "w") as csv_file: 存在问题。一个spurious carriage return char is inserted,在每行之后创建一个空行。

    您必须按照文档中的说明添加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 版本不再需要此功能,但文档继续说明)

    【讨论】:

    【解决方案2】:

    当您打开文件时,您需要使用空白字符串传递关键字参数换行符。这将防止在行之间添加换行符。你的功能应该是:

    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 上的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多