简体   繁体   English

如何从列表和字符串组合中打印csv而没有空格分隔符?

[英]How to print csv from list and string combination without delimiter of space?

my csv file is created using values from a table as: 我的csv文件是使用表中的值创建的,如下所示:

with open(fullpath,'wb') as csvFile:
                    writer = csv.writer(csvFile,delimiter='|',
                                        escapechar=' ',
                                        quoting=csv.QUOTE_NONE)

string_values = 'abc|xyz|mno'

for obj in queryset.iterator():
     writer.writerow([
                 smart_str(obj.code),#code
                 smart_str(string_values),# string of values
                 ])

The csv generated should output result as: 生成的csv应将结果输出为:

code1|abc|xyz|mno

but what is generated is: 但是生成的是:

code1|abc |xyz |mno

I am unable to remove the space from the string while creating the csv. 创建csv时,无法从字符串中删除空格。 in whatever way may be. 无论如何。 The string values are generated dynamically and can have 1 or more string values. 字符串值是动态生成的,可以具有1个或多个字符串值。 I cannot use quoting=csv.QUOTE_NONE without specyfying escapechar=' ' ie a space. 我不能在没有特殊说明的情况下使用quoting = csv.QUOTE_NONE,即空格。 Please suggest. 请提出建议。

You can't just write strings containing the delimiter, unescaped! 您不能只写包含定界符且未转义的字符串!

Use, instead: 改为使用:

string_values = 'abc|xyz|mno'.split('|')

for obj in queryset.iterator():
     writer.writerow([smart_str(obj.code)] + string_values)

IOW, writerow a list of strings, and let the writer insert the delimiters between the strings in the list! IOW, writerow一个字符串列表 ,然后让writer在列表中的字符串之间插入定界符!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不删除分隔符的情况下将字符串拆分为列表 - How do I split a string into a list without removing the delimiter 如何将同时具有逗号和空格分隔符的 CSV 文件转换为仅具有空格分隔符的 csv - How to convert CSV file which having both comma and space delimiter to csv with only space delimiter 从CSV读取:分隔符必须是字符串,而不是unicode - Reading from CSV: delimiter must be a string, not unicode 如何从字符串中获取唯一值而不删除分隔符 - How to get unique values from a string without removing the delimiter 将以空格作为分隔符的.txt 转换为以逗号作为分隔符的.csv - converting .txt with space as delimiter to .csv with comma as delimiter 如何在.csv中将“,”指定为3个字符的分隔符字符串? - How to specify “,” as 3-character delimiter string in .csv? 如何将具有逗号分隔符的 CSV 文件转换为仅具有空格分隔符的 csv - How to convert CSV file which having comma delimiter to csv with only space delimiter CSV导入到Python中的空格分隔符 - Space delimiter in CSV import to Python 如何用带有逗号分隔符和空格的pandas解析csv? - How do I parse a csv with pandas that has a comma delimiter and space? Python如何使用分割定界符删除CSV上的空白 - Python how to use split delimiter to remove white-space on csv
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM