带有自定义分隔符的 CSV 文件
默认情况下,逗号用作 CSV 文件中的分隔符。但是,某些 CSV 文件可以使用逗号以外的分隔符。很少有流行的是|
and \t
。
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
输出:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
编写带引号的 CSV 文件
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
输出:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
如您所见,我们已经传递csv.QUOTE_NONNUMERIC
了quoting
参数。它是csv
模块定义的常量。
csv.QUOTE_NONNUMERIC
指定writer
应在非数字条目周围添加引号的对象。
您可以将其他 3 个预定义常量传递给quoting
参数:
csv.QUOTE_ALL
- 指定writer
要写入 CSV 文件的对象,并在所有条目周围加上引号。
csv.QUOTE_MINIMAL
- 指定writer
对象只引用那些包含特殊字符的字段(分隔符、引号字符或行终止符中的任何字符)
csv.QUOTE_NONE
- 指定writer
不应引用任何条目的对象。它是默认值。
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
输出:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
在这里,我们可以看到该quotechar='*'
参数指示writer
对象*
用作所有非数字值的引号。