简体   繁体   中英

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

my csv file is created using values from a table as:

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:

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. in whatever way may be. The string values are generated dynamically and can have 1 or more string values. I cannot use quoting=csv.QUOTE_NONE without specyfying escapechar=' ' ie a space. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM