2017-10-06 130 views
0

我有一個.csv文件,我需要用列表中的新值覆蓋某個列。使用python寫入特定列是.csv文件

比方說,我有列表L1 = ['La','Lb','Lc'],我想寫在列號。 5的.csv文件。

如果我運行:

L1 = ['La', 'Lb', 'Lc'] 
import csv 
with open(r'C:\LIST.csv','wb') as f: 
    w = csv.writer(f) 
    for i in L1: 
     w.writerow(i) 

這將寫入L1值到第一和第二列。

第一列將是「L」,「L」,「L」和第二列「一個」,「B」,「C」

我找不到的語法要寫入每個特定的列元素從列表中。 (這是在Python 2.7中)。感謝您的幫助!

(這個劇本我必須使用IronPython的,只是內置在自帶的IronPython庫)

+0

你可以結合讀寫。從源文件中讀取每行,對某個列應用更改並將其寫入目標文件,並在最後將dest文件重命名爲源文件。 – rsm

+0

謝謝。我知道該怎麼做,但我不知道如何將我的列表寫入.csv – alc

回答

0

雖然你當然可以使用Python的內置csv模塊讀取數據,修改它,並把它寫我推薦出色的tablib模塊:

from tablib import Dataset 

csv = '''Col1,Col2,Col3,Col4,Col5,Col6,Col7 
a1,b1,c1,d1,e1,f1,g1 
a2,b2,c2,d2,e2,f2,g2 
a3,b3,c3,d3,e3,f3,g3 
''' 

# Read a hard-coded string just for test purposes. 
# In your code, you would use open('...', 'rt').read() to read from a file. 
imported_data = Dataset().load(csv, format='csv') 

L1 = ['La', 'Lb', 'Lc'] 

for i in range(len(L1)): 
    # Each row is a tuple, and tuples don't support assignment. 
    # Convert to a list first so we can modify it. 
    row = list(imported_data[i]) 

    # Put our value in the 5th column (index 4). 
    row[4] = L1[i] 

    # Store the row back into the Dataset. 
    imported_data[i] = row 

# Export to CSV. (Of course, you could write this to a file instead.) 
print imported_data.export('csv') 

# Output: 
# Col1,Col2,Col3,Col4,Col5,Col6,Col7 
# a1,b1,c1,d1,La,f1,g1 
# a2,b2,c2,d2,Lb,f2,g2 
# a3,b3,c3,d3,Lc,f3,g3 
+0

中的特定列。再次感謝。不幸的是,這個腳本必須在IronPython上運行,所以這就是我提到Python 2.7的原因,因爲IronPython類似於2.7(所以沒有熊貓等)。我只能在IronPython中使用默認庫。 – alc

+0

'tablib'與IronPython在某些方面是不兼容的嗎?或者爲什麼你只能使用內置庫? – smarx

+0

謝謝你的建議/問。該腳本將在我無權訪問的計算機上運行(我可以)安裝特定的庫或執行任何其他自定義。所以我必須使用默認安裝的w/IronPython。 'tablib'不在IronPython的Lib文件夾中 – alc