1

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

1
  • Read them in and then take two slices rows[:136] and rows[136:] Commented Jun 3, 2017 at 20:28

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution! Would the approach be the same if I was using pandas and its read csv function?
@wolverinejohn You can slice the file iterator directly and pass the slice to the csv read function of pandas.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.