将数据从Python列表逐行写入 CSV
逗号分隔值 (CSV) 文件是一种纯文本文档,其中表格信息是使用特定格式构建的。 CSV 文件是一种有界文本格式,它使用逗号分隔值。将数据从列表写入 CSV 文件的最常用方法是writer
和DictWriter
类的writerow()
方法。
示例 1:
创建一个 CSV 文件并使用writer
类将数据逐行写入其中。
# Importing library
import csv
# data to be written row-wise in csv fil
data = [['Geeks'], [4], ['geeks !']]
# opening the csv file in 'w+' mode
file = open('g4g.csv', 'w+', newline ='')
# writing the data into the file
with file:
write = csv.writer(file)
write.writerows(data)
输出:
示例 2:
使用DictWriter
类将数据逐行写入现有 CSV 文件。
# importing library
import csv
# opening the csv file in 'w' mode
file = open('g4g.csv', 'w', newline ='')
with file:
# identifying header
header = ['Organization', 'Established', 'CEO']
writer = csv.DictWriter(file, fieldnames = header)
# writing data row-wise into the csv file
writer.writeheader()
writer.writerow({'Organization' : 'Google',
'Established': '1998',
'CEO': 'Sundar Pichai'})
writer.writerow({'Organization' : 'Microsoft',
'Established': '1975',
'CEO': 'Satya Nadella'})
writer.writerow({'Organization' : 'Nokia',
'Established': '1865',
'CEO': 'Rajeev Suri'})
输出:
示例 3:
使用writer
类将数据逐行添加到现有 CSV 文件中。
# Importing library
import csv
# data to be written row-wise in csv fil
data = [['Geeks for Geeks', '2008', 'Sandeep Jain'],
['HackerRank', '2009', 'Vivek Ravisankar']]
# opening the csv file in 'a+' mode
file = open('g4g.csv', 'a+', newline ='')
# writing the data into the file
with file:
write = csv.writer(file)
write.writerows(data)
输出: