简体   繁体   中英

Python codecs has space between every character, how to remove

I am trying to write a list of tuples to a CSV file. I want to use codecs because of UTF-8 issues in csv module. I am using python 2.7.13

The code write fine but when i open the file, i see a space between every character even when i didnt put any space. How do i remove the space? using replace or strip doesnt work.

import codecs

tup_list = [('a','b','c',123,456),('d','e','f',789,101)]

write each row to the codecs file

f = codecs.open("test2.csv", "w", "utf-8")
for row in tup_list:
    print >> f,row[0],",",row[1],",",row[2],",",row[3],",",row[4]

open the file

with open('test2.csv','rb') as f:
    for row in f:
    print row

output

a , b , c , 123 , 456

d , e , f , 789 , 101

Either:

f.write('{}\n'.format(','.join(row)))

Or, my personal favorite:

import csv

with open('test2.csv', 'wb') as f:
   writer = csv.writer(f)
   for row in tup_list:
      writer.writerow(row)

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