Reputation: 29
I'm trying to split a CSV file that has 201 rows. The first 136 rows contains information that is different from the remaining 65 rows. Is there anyway I can split the CSV file after 136 rows?
The solutions I have found so far split the file evenly. I have looked into this as a possible solution as well: https://gist.github.com/jrivero/1085501
Upvotes: 1
Views: 1258
Reputation: 11
If you know the number of lines you need to skip you can use csvreader.line_num
to know the line you're reading, you can find more info about it here: https://docs.python.org/2/library/csv.html#reader-objects
Upvotes: 1
Reputation: 78554
You can use two csv.reader
objects on your file object. Slice the first reader object up to the specified number of rows using itertools.islice
, and then read the rest of the rows using the second reader.
If the two parts are different by say delimiters, the two csv.reader
objects can easily handle this:
import csv
from itertools import islice
with open('your_file_name.csv') as f:
first_rows = list(islice(csv.reader(f), None, 136))
last_rows = list(csv.reader(f, delimiter=';')) # use a different delim or quote char
Upvotes: 3