Search code examples
pythoncsvfiledelete-rowreadlines

How to delete specific data from single line in CSV FILE and last line?


I have a CSV file that I have successfully removed lines from using the following code:

    myfiles = glob.glob('myfile.csv')
    
    for file in myfiles:
        lines = open(file).readlines()
        open(file, 'w').writelines(lines[27:])

Now what remains in the CSV file is the following:

"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10"

"Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"

"Copy of Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"

What I want to do:

I have been trying to edit the CSV file using the code above to completely delete line 6 but don't know how to add it to the code above and also edit Line 2 and line 4 to remove the last 3 three contents of the line (F8,F9,F10 and 1000,2000,3000 respectively) --> so the CSV should look like the following below:

"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7"

"Football weights", "8", "10", "11", "120", "10", "21", "20"

Thank you in advance if anyone can give me some pointers or tips.


Solution

  • Use the csv module to read and rewrite back without the last 3 columns

    for file in myfiles:
        rows = []
    
        with io.open(file,"r",encoding="utf-8") as f:
            reader = csv.reader(f, delimiter=",", quotechar='"')
    
            for row in reader:
                rows.append(row[:-3])
    
        with io.open(file,"w",encoding="utf-8") as f:
            writer = csv.writer(f)
            
            for row in rows:
                writer.writerow(row)