1

次の文字列を含む変数があります。

fruit_wanted = 'banana,apple'

csvファイルもあります

fruit,'orange','grape','banana','mango','apple','strawberry'
number,1,2,3,4,5,6
value,3,2,2,4,2,1
price,3,2,1,2,3,4

「fruit_wanted」変数に「fruit」がリストされていない列を削除するにはどうすればよいですか?

アウトファイルが次のようになるように

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

ありがとうございました。

4

2 に答える 2

7

DictReader()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)
于 2012-11-28T21:43:35.790 に答える
0

ここにいくつかの擬似コードがあります:

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
于 2012-11-28T21:43:53.650 に答える