Python在打印到CSV时跳过行
问题描述:
我正在尝试创建.csv文件。Python在打印到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版本(在Windows上)具有与with open(path, "w") as csv_file:
的问题。 A spurious carriage return char is inserted,在每行之后创建一个空行。
您必须按照文档中的说明添加newline=""
。 Python的3:
with open(path, "w",newline="") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
至于蟒2:
with open(path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
还看到:
- portable way to write csv file in python 2 or python 3
- csv writer expected byte like and space between rows
(注意,最新的Python版本Windows上的sions不再需要这个,但文档继续说明它)
答
当您打开文件时,您需要将关键字参数换行符传递给空白字符串。这将防止在行之间添加换行符。您的功能应为:
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上的一个问题。
该问题特定于Windows,并在[documentation](https://docs.python.org/3/library/csv.html#id3) – Aaron