2016-08-02 40 views
2
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是這個我需要的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行,在 J = i.replace(」」,‘’) AttributeError的:‘名單’對象有沒有屬性‘取代’

林超新在此這樣的IM可能擰多的事情了,只是需要一些指導。

我最終想要的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'] 
+0

'I [0] .replace( ...)' – handle

+0

別忘了關閉你的文件,或者使用'with'語句(https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) – handle

回答

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']] 
+0

是的,這正是我需要的。現在只需將新讀者寫入新的csv。 – dergatroid

+0

如果這是你需要的,你可以接受答案......(按下V標誌) –

0

試試這個。我可能會關閉與slicing

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