简体   繁体   English

打印到CSV时Python跳过行

[英]Python skips line when printing to CSV

I am trying to create .csv file. 我正在尝试创建.csv文件。

For some reason it skips line before printing entry. 由于某些原因,它会在打印条目之前跳过行。

Here is the output 这是输出

在此处输入图片说明

But here is what I need 但是这就是我所需要的

在此处输入图片说明

Below is code. 下面是代码。 Apparently if line != "": doesn't work 显然, 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)

Some python versions (on windows) have an issue with that with open(path, "w") as csv_file: . 某些python版本(在Windows上)在with open(path, "w") as csv_file: A spurious carriage return char is inserted , creating a blank line after each line. 插入了一个错误的回车符char ,在每行之后创建一个空行。

You have to add newline="" as stated in the documentation. 您必须按照文档中所述添加newline="" Python 3: Python 3:

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

As for python 2: 至于python 2:

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

see also: 也可以看看:

(note that latest Python versions on Windows don't need this anymore, but the documentation continues to state it) (请注意,Windows上的最新Python版本不再需要此功能,但是文档继续说明这一点)

When you open the file you need to pass the keyword argument newline with a blank string. 当您打开文件时,您需要传递带有空白字符串的关键字参数newline。 This will prevent the newlines being added between rows. 这将防止在行之间添加换行符。 Your function should be: 您的功能应为:

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)

Note that this is only an issue on Windows. 请注意,这仅是Windows上的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM