Python 从CSV中动态删除列

Python 从CSV中动态删除列,python,Python,我想从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 使用enumerate获取列索引,并创建一个不包含不

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

使用
enumerate
获取列索引,并创建一个不包含不需要的列的新行。。。例如:

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

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

使用
枚举
获取列索引,并创建一个不包含您不需要的列的新行。。。例如:

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

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

读取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)

删除列后,读取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)

我需要保存文件还是在此过程中完成此操作。@user7您需要打开一个文件进行写入,并创建一个
csv.writer
,然后使用
.writerow()
-请参阅我需要保存文件还是在此过程中完成此操作。@user7您需要打开一个文件进行写入,并创建一个
csv.writer
,并使用
.writerow()
-请记住
csv
不会为您关闭文件。除此之外,还有一个很好的例子:csv.writer打开的fileobj应该以二进制模式打开,例如:
'wb'
@thavan确实如此-但我会指出:
如果csvfile是一个文件对象,在有区别的平台上,必须使用“b”标志打开该文件。
-由于在不需要的地方它没有区别,因此通常建议使用它,因为
csv
不会为您关闭该文件。除此之外,还有一个很好的例子:csv.writer打开的fileobj应该以二进制模式打开,例如:
'wb'
@thavan确实如此-但我会指出:
如果csvfile是一个文件对象,在有区别的平台上,它必须使用“b”标志打开。
-由于在不需要它的地方它没有区别,因此通常建议无论如何使用它