2017-09-05 136 views
2

我正在嘗試創建.csv文件。Python在打印到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) 

回答

3

一些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=',') 

還看到:

(注意,最新的Python版本Windows上的sions不再需要這個,但文檔繼續說明它)

+0

該問題特定於Windows,並在[documentation](https://docs.python.org/3/library/csv.html#id3) – Aaron

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上的一個問題。