我正在尝试创建.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)
答案 0 :(得分:3)
某些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版本不再需要此版本,但文档会继续说明)
答案 1 :(得分: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上的一个问题。