Python – 将列表字典写入 CSV
在本文中,我们将讨论如何将列表字典写入 CSV 的实际实现。
我们可以为此使用 csv 模块。 csvwriter文件对象支持csvwriter.writerow()、csvwriter.writerows()、csvwriter.writeheader()三种方法。
语法:
csv.writer(csvfile, dialect='excel')
参数:
- csvfile:具有 write() 方法的文件对象。
- dialect(可选):要使用的方言的名称。
方法 1:使用 csv.writerow()
要将列表字典写入 CSV 文件,必要的函数是 csv.writer()、csv.writerow()。此方法一次写入一行。可以使用此方法写入字段行。
句法 :
csvwriter.writerow(row)
示例 1 :
Python3
# import the csv package
import csv
# create a csv file with desired name and
# store it in a variable
with open('test.csv', 'w') as testfile:
# pass the the temporary variable to
# csv.writer function
csvwriter = csv.writer(testfile,)
# use writerow function to insert a
# single row to the csv file.
csvwriter.writerow(['col1', 'col2', 'col3',
'col4', 'col5'])
Python3
# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
'height': [143, 163, 144, 154, 174, 177],
'weight': [77, 66, 59, 53, 71, 63], }
# create a csv file called test.csv and
# store it a temp variable as outfile
with open("test.csv", "w") as outfile:
# pass the csv file to csv.writer.
writer = csv.writer(outfile)
# convert the dictionary keys to a list
key_list = list(test.keys())
# find th length of the key_list
limit = len(key_list)
# the length of the keys corresponds to
# no. of. columns.
writer.writerow(test.keys())
# iterate each column and assign the
# corresponding values to the column
for i in range(limit):
writer.writerow([test[x][i] for x in key_list])
Python3
# import the csv package
import csv
# create a file called test.csv
# and store it in a temporary variable
with open('test.csv', 'w') as testfile:
# pass the temp variable to csv.writer
# function
csvwriter = csv.writer(testfile)
# pass the row values to be stored in
# different rows
csvwriter.writerows([['row1'], ['row2'], ['row3'],
['row4'], ['row5'], ['row6']])
Python3
# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
'height': [143, 163, 144, 154, 174, 177],
'weight': [77, 66, 59, 53, 71, 63], }
# create a csv file test.csv and store
# it in a variable as outfile
with open("test.csv", "w") as outfile:
# pass the csv file to csv.writer function.
writer = csv.writer(outfile)
# pass the dictionary keys to writerow
# function to frame the columns of the csv file
writer.writerow(test.keys())
# make use of writerows function to append
# the remaining values to the corresponding
# columns using zip function.
writer.writerows(zip(*test.values()))
Python3
# import the csv package
import csv
# create a csv file with desired name
#and store it in a variable
with open('test.csv', 'w') as testfile:
# store the desired header row as a list
# and store it in a variable
fieldnames = ['first_field', 'second_field', 'third_field']
# pass the created csv file and the header
# rows to the Dictwriter function
writer = csv.DictWriter(testfile, fieldnames=fieldnames)
# Now call the writeheader function,
# this will write the specified rows as
# headers of the csv file
writer.writeheader()
输出:
或者,可以仅使用 csv.writerow()函数将列表字典转换为 CSV 文件,只需遍历字典中的每个键值对,如图所示
示例 2:
Python3
# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
'height': [143, 163, 144, 154, 174, 177],
'weight': [77, 66, 59, 53, 71, 63], }
# create a csv file called test.csv and
# store it a temp variable as outfile
with open("test.csv", "w") as outfile:
# pass the csv file to csv.writer.
writer = csv.writer(outfile)
# convert the dictionary keys to a list
key_list = list(test.keys())
# find th length of the key_list
limit = len(key_list)
# the length of the keys corresponds to
# no. of. columns.
writer.writerow(test.keys())
# iterate each column and assign the
# corresponding values to the column
for i in range(limit):
writer.writerow([test[x][i] for x in key_list])
输出:
方法 2:使用 csv.writerows()
要将列表字典写入 CSV 文件,必要的函数是 csv.writer()、csv.writerows()。此方法将行中的所有元素(如上所述的行对象的可迭代)写入写入者的文件对象。
句法
csvwriter.writerows(rows)
示例 1 :
Python3
# import the csv package
import csv
# create a file called test.csv
# and store it in a temporary variable
with open('test.csv', 'w') as testfile:
# pass the temp variable to csv.writer
# function
csvwriter = csv.writer(testfile)
# pass the row values to be stored in
# different rows
csvwriter.writerows([['row1'], ['row2'], ['row3'],
['row4'], ['row5'], ['row6']])
输出:
示例 2:
在这里,我们将创建一个 csv 文件 test.csv 并将其作为 outfile 存储在一个变量中。
Python3
# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
'height': [143, 163, 144, 154, 174, 177],
'weight': [77, 66, 59, 53, 71, 63], }
# create a csv file test.csv and store
# it in a variable as outfile
with open("test.csv", "w") as outfile:
# pass the csv file to csv.writer function.
writer = csv.writer(outfile)
# pass the dictionary keys to writerow
# function to frame the columns of the csv file
writer.writerow(test.keys())
# make use of writerows function to append
# the remaining values to the corresponding
# columns using zip function.
writer.writerows(zip(*test.values()))
输出:
方法 3:使用 csv.writeheader()
此方法将指定字段名称的行写入 csv.dictwriter 对象的标题。
句法
csvwriter.writeheader()
示例:
Python3
# import the csv package
import csv
# create a csv file with desired name
#and store it in a variable
with open('test.csv', 'w') as testfile:
# store the desired header row as a list
# and store it in a variable
fieldnames = ['first_field', 'second_field', 'third_field']
# pass the created csv file and the header
# rows to the Dictwriter function
writer = csv.DictWriter(testfile, fieldnames=fieldnames)
# Now call the writeheader function,
# this will write the specified rows as
# headers of the csv file
writer.writeheader()
输出: