Search code examples
pythoncsvrowdelete-row

How to delete rows from a CSV file when I just know the row number?


I am a beginner and currently writing a code in python where if the CSV's length gets more than a given number, the first row will be deleted, making space for more. Is there a function that can delete rows in a CSV just by row number?


Solution

  • There is no special function for that since that can be done with a simple for loop.

    Here we have an input file which is read line by line while skipping the lines with the row number contained in rownumbers_to_remove. Notice the enumerate(...) with the start=1 parameter to make the index start at 1 instead of 0. This might improve readability a bit.

    lines = list()
    rownumbers_to_remove= [5,6]
    
    with open('name-of-file.csv', 'r') as read_file:
        reader = csv.reader(read_file)
        for row_number, row in enumerate(reader, start=1):
            if(row_number not in rownumbers_to_remove):
                lines.append(row)
    
    with open('name-of-file.csv', 'w') as write_file:
        writer = csv.writer(write_file)
        writer.writerows(lines)