[英]Writing To CSV file Without Line Space in Python 3
I am trying out the program for writing to a CSV file.我正在尝试写入 CSV 文件的程序。
Here's my code:这是我的代码:
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)
The program runs well.该程序运行良好。 But in the CSV file, there is a blank newline space (without any entries) between each entry .
但是在 CSV 文件中,每个条目之间有一个空白的换行符(没有任何条目) 。 How to eliminate that line in the resultant CSV file?
如何消除生成的 CSV 文件中的那一行?
Recommended implementation per Python3 Documentation.根据 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 https://docs.python.org/3/library/csv.html#csv.writer
Method 1 So when ever i write csv files spaces between lines are created and when reading the files they create problems for me So here is how i solved it方法 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
Method 2 Or even simpler you can use Dictreader works fine without error even if spaces are preset方法 2 或者甚至更简单,即使预设了空格,您也可以使用 Dictreader 正常工作而不会出错
with open("Location.csv","r") as obj:
reader=csv.DictReader(obj)
for lines in reader:
print(lines["Code"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.