当使用CSV模块将行解析为CSV文件时,如果字段文本中存在\n,则这将在生成的CSV文件中创建换行符. 请考虑以下代码:
import csv
field_names=['id', 'number', 'scope']
data_rows=[
{'id': 100001, 'number': 'a01', 'scope': 'row1 test \n\nrow1 test\n\nrow1 test'},
{'id': 100002, 'number': 'a02', 'scope': 'row2 test \n\nrow2 test\n\nrow2 test'}
]
tbl_name= 'testnewlines'
with open(tbl_name+'.csv','w', newline='', encoding='utf-8') as f:
writer=csv.DictWriter(f,fieldnames=field_names,delimiter='|')
writer.writeheader()
for d_row in data_rows:
writer.writerow(d_row)
生成的CSV文件如下所示
id|number|scope
100001|a01|"row1 test
row1 test
row1 test"
100002|a02|"row2 test
row2 test
row2 test"
如果\n包含在带引号的文本中,如何避免在CSV文件中创建换行符? 在模块文档https://docs.python.org/3/library/csv.html的脚注中 建议使用newline=‘’,但不适用于我.