我需要删除CSV行中的空格,然后将逗号添加到指定的字符位置

时间:2016-08-02 14:13:26

标签: python csv

import csv
import sys

f = open(sys.argv[1], 'rb') 

reader = csv.reader(f)

k = []

for i in reader:
    j = i.replace(' ','')
    k.append(j)

print k

原始CSV就是这个

['1 323 104 564 382']
['2 322 889 564 483']
['3 322 888 564 479']
['4 322 920 564 425']
['5 322 942 564 349']
['6 322 983 564 253']
['7 322 954 564 154']
['8 322 978 564 121']

我想让它看起来像这样:

['1323104564382']
['2322889564483']
['3322888564479']
['4322920564425']
['5322942564349']
['6322983564253']
['7322954564154']
['8322978564121']

我收到以下错误:

追踪(最近一次通话): 文件“list_replace.py”,第12行,in j = i.replace('','') AttributeError:'list'对象没有属性'replace'

我是超级新手,所以我可能会搞砸多个事情,只需要一些指导。

我最终希望csv看起来像下面的文字,但我一步一个步骤

['1,323104,564382']
['2,322889,564483']
['3,322888,564479']
['4,322920,564425']
['5,322942,564349']
['6,322983,564253']
['7,322954,564154']
['8,322978,564121']

2 个答案:

答案 0 :(得分:0)

试试这个。我可能会关注slicing

parts= i[0].split()
one=parts[0]
two=parts[1:2+1]
three=parts[3:4+1]
j= ",".join( [one,two,three] )

答案 1 :(得分:0)

[[i[0].replace(' ','')] for i in reader]

并达到你的最终目标:

reader=[[i[0].replace(' ',',',1)] for i in reader]
reader=[[i[0].replace(' ','',1)] for i in reader]
reader=[[i[0].replace(' ',',',1)] for i in reader]
reader=[[i[0].replace(' ','',1)] for i in reader]

得到:

[['1,323104,564382'],
 ['2,322889,564483'],
 ['3,322888,564479'],
 ['4,322920,564425'], 
 ['5,322942,564349'],
 ['6,322983,564253'],
 ['7,322954,564154'],
 ['8,322978,564121']]