在python中删除选定的csv列

2024-10-01 15:40:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量,它包含一个字符串:

fruit_wanted = 'banana,apple'

我还有一个csv文件

^{pr2}$

现在我该如何删除“fruit”没有在“fruit”变量中列出的列?在

所以外场看起来像

fruit,'banana','apple'
number,3,5
value,2,2
price,1,3

谢谢。在


Tags: 文件csv字符串numberapplevaluepricebanana
2条回答

以下是一些伪代码:

open the original CSV for input, and the new one for output
read the first row of the original CSV and figure out which columns you want to delete
write the modified first row to the output CSV
for each row in the input CSV:
    delete the columns you figured out before
    write the modified row to the output CSV

使用^{} class读取csv文件,忽略不需要的列:

fruit_wanted = ['fruit'] + ["'%s'" % f for f in fruit_wanted.split(',')]
outfile = csv.DictWriter(open(outputfile, 'wb'), fieldnames=fruit_wanted)
fruit_wanted = set(fruit_wanted)

for row in csv.DictReader(open(inputfile, 'rb')):
    row = {k: row[k] for k in row if k in fruit_wanted}
    outfile.writerow(row)

相关问题 更多 >

    热门问题