在 Python 3 中写入无行 Space 的 CSV 文件

Writing To CSV file Without Line Space in Python 3

我正在试用写入 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 文件中,每个条目 之间有一个 空白换行符 space(没有任何条目)。 如何删除生成的 CSV 文件中的 行?

根据 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 因此,每当我编写 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

方法二 或者更简单,即使预设了空格,您也可以使用 Dictreader 正常工作而不会出错

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