简体   繁体   English

Python编解码器每个字符之间都有空格,如何删除

[英]Python codecs has space between every character, how to remove

I am trying to write a list of tuples to a CSV file. 我正在尝试将元组列表写入CSV文件。 I want to use codecs because of UTF-8 issues in csv module. 由于csv模块中存在UTF-8问题,我想使用编解码器。 I am using python 2.7.13 我正在使用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. 使用replacestrip不起作用。

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)

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

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