在Python 3中写入没有行空间的CSV文件

时间:2016-12-10 07:32:09

标签: python-3.x csv newline

我正在尝试编写CSV文件的程序。

这是我的代码:

import csv
#field names
fields = ['Name','Branch','Year']
# data rows of CSV file
rows = [['Stef', 'Multimedia Technology','2'],
    ['Kani', 'Information Technology', '2'],
    ['Plazaa', 'Electronics Engineering', '4'],
     ['Lizzy', 'Computer Science', '4'],
     ['Reshmi', 'Multimedia Technology', '3'],
     ['Geetha','Electrical Engineering', '4'],
     ['Keerti', 'Aeronautical Engineering', '3']]

#writing to csv file
#writing to csv file
with open('records.csv','w') as csvfile:
    #creating  a csv writer object
    csvwriter = csv.writer(csvfile)
    #writing the fields
    csvwriter.writerow(fields)
    # writing the data rows
    csvwriter.writerows(rows)

该计划运行良好。但是在CSV文件中,每个条目之间都有空白换行符空格(没有任何条目)如何消除生成的CSV文件中的行?

2 个答案:

答案 0 :(得分:4)

根据Python3文档推荐的实现。

with open('records.csv','w', newline='') as csvfile:
    #creating  a csv writer object
    csvwriter = csv.writer(csvfile)
    #writing the fields
    csvwriter.writerow(fields)
    # writing the data rows
    csvwriter.writerows(rows)

https://docs.python.org/3/library/csv.html#csv.writer

答案 1 :(得分:1)

方法1因此,每当我编写csv文件时,都会在行之间创建空格,并且在读取文件时它们会为我创建问题,所以这是我如何解决

with open("Location.csv","r") as obj:
            reader=csv.reader(obj)
            for lines in reader:
                try:
                    print(lines["Code"])
                    print(lines["Key_num"])
                except TypeError:
                    pass

方法2 甚至更简单,即使预设了空格,您也可以使用Dictreader正常工作而不会出现错误

with open("Location.csv","r") as obj:
              reader=csv.DictReader(obj)
              for lines in reader:
                    print(lines["Code"])