I want to be able to specify how many rows I want to keep and delete the rest, also preserving the header.
I found some code which let’s you delete the first 5 rows but how can I make it do what I want?
JavaScript
x
4
1
with open ('myfile.csv', 'wb') as outfile:
2
outfile.writelines(data_in[1])
3
outfile.writelines(data_in[5:])
4
For example if I have this CSV
JavaScript
1
9
1
6.5, 5.4, 0, 000
2
6.5, 5.4, 1, 610
3
1.2, 4.0, 0, 530
4
3.2, 5.4, 1, 330
5
4.2, 3.0, 0, 320
6
5.5, 2.3, 1, 780
7
1.3, 4.4, 0, 520
8
5.3, 1.0, 0, 420
9
I just want to specify a number to my script… let’s say (2) and it will KEEP 2 rows and remove all others
output would become:
JavaScript
1
3
1
6.5, 5.4, 0, 000
2
6.5, 5.4, 1, 610
3
Can i also make it save it with a different name?
Advertisement
Answer
If you first read your original CSV-file into variable data_in
with commands
JavaScript
1
3
1
with open('my_original_file.csv') as inp:
2
data_in = inp.readlines()
3
you may continue:
JavaScript
1
5
1
n = int(input("How many rows after header you want to write: "))
2
3
with open('myfile.csv', 'w') as outfile:
4
outfile.writelines(data_in[:n+1])
5
This will write
- the header row —
data_in[0]
, and - subsequent n rows —
data_in[1]
todata_in[n]