0

我想从 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 
4

2 回答 2

3

用于enumerate获取列索引,并创建一个没有您不想要的列的新行...例如:

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

csv.writer然后用某处写出你的行......

于 2013-04-22T11:32:26.727 回答
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)
于 2013-04-22T11:49:59.233 回答