2017-10-06 148 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