Skip to content
Advertisement

keep x rows and delete all from csv file

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

For example if I have this CSV

JavaScript

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

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

you may continue:

JavaScript

This will write

  • the header row — data_in[0], and
  • subsequent n rows — data_in[1] to data_in[n]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement