2013-04-22 99 views
0

我想动态地从CSV中删除列,这是我迄今为止所做的。我不知道在哪里,从这里走,但:从CSV动态删除列

# Remove column not needed. 
column_numbers_to_remove = 3,2, 
file = upload.filepath 
#I READ THE FILE 
file_read = csv.reader(file) 

REMOVE 3 and 2 column from the CSV 
UPDATE SAVE CSV 

回答

3

使用enumerate拿到列索引,并创建一个新的行没有你不想要的列...如:

for row in file_read: 
    new_row = [col for idx, col in enumerate(row) if idx not in (3, 2)] 

然后使用csv.writer在某处写出您的行...

+0

我是否需要保存该文件或在此过程中完成此操作。 – GrantU 2013-04-22 11:36:33

+0

@ user7您将需要打开一个文件进行写入,并创建一个'csv.writer',并使用'.writerow()' - 参见http://docs.python.org/2/library/csv.html# csv.writer – 2013-04-22 11:38:24

1

读取csv并在删除列后写入另一个文件。

import csv 
creader = csv.reader(open('csv.csv')) 
cwriter = csv.writer(open('csv2.csv', 'w')) 

for cline in creader: 
    new_line = [val for col, val in enumerate(cline) if col not in (2,3)] 
    cwriter.writerow(new_line) 
+0

请记住'csv'不会为你关闭文件。否则就是一个很好的例子 – jamylak 2013-04-22 11:56:38

+0

另外:由csv.writer打开的fileobj应该以二进制模式打开,例如:''wb'' – 2013-04-22 11:59:59

+0

@JonClements它在没有'wb'模式下工作。 – thavan 2013-04-22 12:02:12