Delete or remove last column in CSV file using Python

前端 未结 2 941
生来不讨喜
生来不讨喜 2021-01-12 10:22

I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I\'m missing, or do I have to loop through al

相关标签:
2条回答
  • 2021-01-12 10:41

    Use the csv module. When writing out a row, use row[:-1] to chop off the last item:

    import csv
    
    with open(filename,"r") as fin:
        with open(outname,"w") as fout:
            writer=csv.writer(fout)
            for row in csv.reader(fin):
                writer.writerow(row[:-1])
    
    0 讨论(0)
  • 2021-01-12 10:42

    Even if you don't use CSV module, the logical and sane way is to read the file row by row, split them on comma, and print out item 1 through 4 with a join. eg

    for line in open("file"):
        print ','.join( line.split(",")[:-1] )
    

    Or just by simple string indexing

    for line in open("file"):
        print line[ : line.rindex(",") ]
    
    0 讨论(0)
提交回复
热议问题