我想将列表列表传输/写入txt文件。列表中的某些字符串包含引号,也应该转移。
但是如果我尝试在txt文件中编写它们,它们在字符串之前和之后包含三个引号。如何在不手动操作的情况下将"""3"""
更改为"3"
并将"""A1"""
更改为"A1"
? (列表列表包含65.000个列表...)没有引号的数字应该保持不变。
import csv
results = ['"3"', '"300.096"', '"0.033"', '45.4715', '35.903', '1', '0.205328', '0.0702029201671833', '"0"', '"A1"', '"STAR-"'],['"3"', '"300.096"', '"0.033"', '45.4715', '35.903', '1', '0.205328', '0.0702029201671833', '"0"', '"A1"', '"STAR-"']
path = "C:\\Users\\kaza\\Desktop\\Bla.txt"
with open(path, "w") as output:
writer = csv.writer(output, lineterminator='\n')
writer.writerows(A)
我得到的结果看起来像这样
"""3""","""300.096""","""0.033""",45.4715,35.903,1,0.205328,0.0702029201671833,"""0""","""A1""","""STAR-"""
"""3""","""300.096""","""0.033""",45.4715,35.903,1,0.205328,0.0702029201671833,"""0""","""A1""","""STAR-"""`
答案 0 :(得分:2)
您正在使用引号编写数据。默认情况下,csv.writer()
已使用引号字符来围绕可能在值中包含分隔符的数据,并将使用double {{1}转义值中的任何"
个字符在用自己的""
引号围绕值之前标记。
要么不在引号中包含引号(并引用".."
类),要么禁用引号转义。
通过将quoting
设置为csv.QUOTE_NONE
并将quotechar
值设置为csv.writer()
,可以停用引用转义功能:
None
演示:
writer = csv.writer(output, lineterminator='\n',
quoting=csv.QUOTE_NONE, quotechar=None)
当您设置>>> import csv
>>> output = BytesIO()
>>> writer = csv.writer(output, lineterminator='\n', quoting=csv.QUOTE_NONE, quotechar=None)
>>> results = ['"3"', '"300.096"', '"0.033"', '45.4715', '35.903', '1', '0.205328', '0.0702029201671833', '"0"', '"A1"', '"STAR-"'],['"3"', '"300.096"', '"0.033"', '45.4715', '35.903', '1', '0.205328', '0.0702029201671833', '"0"', '"A1"', '"STAR-"']
>>> writer.writerow(results[0])
84L
>>> writer.writerow(results[1])
84L
>>> print(output.getvalue())
"3","300.096","0.033",45.4715,35.903,1,0.205328,0.0702029201671833,"0","A1","STAR-"
"3","300.096","0.033",45.4715,35.903,1,0.205328,0.0702029201671833,"0","A1","STAR-"
时,您可能希望为escapechar
指定一个值,以便可以正确处理值中分隔符或行终止符的任何外观。