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?
Advertisement
Answer
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.
JavaScript
x
13
13
1
lines = list()
2
rownumbers_to_remove= [5,6]
3
4
with open('name-of-file.csv', 'r') as read_file:
5
reader = csv.reader(read_file)
6
for row_number, row in enumerate(reader, start=1):
7
if(row_number not in rownumbers_to_remove):
8
lines.append(row)
9
10
with open('name-of-file.csv', 'w') as write_file:
11
writer = csv.writer(write_file)
12
writer.writerows(lines)
13