我正在尝试将一个元组列表写入CSV文件。我想使用编解码器,因为csv模块中存在UTF-8问题。我使用的是python 2.7.13
代码写得很好,但是当我打开文件时,即使我没有放任何空间,我也会看到每个角色之间的空格。我如何删除空间?使用replace
或strip
无效。
import codecs
tup_list = [('a','b','c',123,456),('d','e','f',789,101)]
将每一行写入编解码器文件
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]
打开文件
with open('test2.csv','rb') as f:
for row in f:
print row
输出
a , b , c , 123 , 456
d , e , f , 789 , 101
答案 0 :(得分:0)
或者:
f.write('{}\n'.format(','.join(row)))
或者,我个人的最爱:
import csv
with open('test2.csv', 'wb') as f:
writer = csv.writer(f)
for row in tup_list:
writer.writerow(row)