简体   繁体   中英

Split CSV file after specified row Python

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

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

如果您知道需要跳过的行数,则可以使用csvreader.line_num来了解正在阅读的行,您可以在此处找到有关此行的更多信息: https : csvreader.line_num .html#reader-objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM