Delete or delete last column in CSV file using Python

I have a 5-column CSV file. How to use Python, how to remove the last column (header5 in the example)? Is there a simple way that I am missing, or do I need to iterate over all the lines in the CSV and remove each value from the last column (which may leave me with an undesirable preceding comma)?

I do not see anything related to this in the CSV module or elsewhere in interwebs, so any help is greatly appreciated.

header1,header2,header3,header4,header5 value1,value2,value3,value4,value5 value1,value2,value3,value4,value5 
+6
source share
2 answers

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

 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]) 
+12
source

Even if you are not using the CSV module, the logical and reasonable way is to read the file line by line, comma-separated, and print elements 1 through 4 using join . eg,

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

Or just using simple row indexing

 for line in open("file"): print line[ : line.rindex(",") ] 
+1
source

Source: https://habr.com/ru/post/896219/


All Articles