How to delete columns in a CSV file?

后端 未结 9 1747
你的背包
你的背包 2020-11-27 18:05

I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will po

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 18:27

    Using a dict to grab headings then looping through gets you what you need cleanly.

    import csv
    ct = 0
    cols_i_want = {'cost' : -1, 'date' : -1}
    with open("file1.csv","rb") as source:
        rdr = csv.reader( source )
        with open("result","wb") as result:
            wtr = csv.writer( result )
            for row in rdr:
                if ct == 0:
                  cc = 0
                  for col in row:
                    for ciw in cols_i_want: 
                      if col == ciw:
                        cols_i_want[ciw] = cc
                    cc += 1
                wtr.writerow( (row[cols_i_want['cost']], row[cols_i_want['date']]) )
                ct += 1
    

提交回复
热议问题