通过Python列表写入CSV会导致数据之间出现空白行

问题描述 投票:0回答:1

我有一个从 python 编写 csv 的示例:

import csv

# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'] 

# data rows of csv file 
rows = [ ['Nikhil', 'COE', '2', '9.0'], 
     ['Sanchit', 'COE', '2', '9.1'], 
     ['Aditya', 'IT', '2', '9.3'], 
     ['Sagar', 'SE', '1', '9.5'], 
     ['Prateek', 'MCE', '3', '7.8'], 
     ['Sahil', 'EP', '2', '9.1']] 

 with open(Test.csv', 'w') as f:
 
# using csv.writer method from CSV package
 
 write = csv.writer(f)
 write.writerow(fields)
 write.writerows(rows)

这工作正常,除了我有以下结果:

Name,Branch,Year,CGPA

Nikhil,COE,2,9.0

Sanchit,COE,2,9.1

Aditya,IT,2,9.3

Sagar,SE,1,9.5

Prateek,MCE,3,7.8

Sahil,EP,2,9.1

正如您在我的 csv 中看到的,数据之间有空白。我不明白这些中断从何而来,知道吗?

python csv export-to-csv
1个回答
1
投票

您可以在您的作家部分添加

newline = ''

import csv

fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [['Nikhil', 'COE', '2', '9.0'],
        ['Sanchit', 'COE', '2', '9.1'],
        ['Aditya', 'IT', '2', '9.3'],
        ['Sagar', 'SE', '1', '9.5'],
        ['Prateek', 'MCE', '3', '7.8'],
        ['Sahil', 'EP', '2', '9.1']]

with open('Test.csv', 'w', newline = '') as f:
    writer = csv.writer(f)
    writer.writerow(fields)
    writer.writerows(rows)
© www.soinside.com 2019 - 2024. All rights reserved.