How to delete columns in a CSV file?

后端 未结 9 1742
你的背包
你的背包 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:28

    you can use the csv package to iterate over your csv file and output the columns that you want to another csv file.

    The example below is not tested and should illustrate a solution:

    import csv
    
    file_name = 'C:\Temp\my_file.csv'
    output_file = 'C:\Temp\new_file.csv'
    csv_file = open(file_name, 'r')
    ## note that the index of the year column is excluded
    column_indices = [0,1,3,4]
    with open(output_file, 'w') as fh:
        reader = csv.reader(csv_file, delimiter=',')
        for row in reader:
           tmp_row = []
           for col_inx in column_indices:
               tmp_row.append(row[col_inx])
           fh.write(','.join(tmp_row))
    

提交回复
热议问题