[英]Split CSV file after specified row Python
I'm trying to split a CSV file that has 201 rows. 我正在尝试拆分具有201行的CSV文件。 The first 136 rows contains information that is different from the remaining 65 rows.
前136行包含与其余65行不同的信息。 Is there anyway I can split the CSV file after 136 rows?
无论如何,我可以在136行之后拆分CSV文件吗?
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
我也将其视为可能的解决方案: https : //gist.github.com/jrivero/1085501
You can use two csv.reader
objects on your file object. 您可以在文件对象上使用两个
csv.reader
对象。 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. 使用
itertools.islice
将第一个阅读器对象切成指定的行数,然后使用第二个阅读器读取其余的行。
If the two parts are different by say delimiters, the two csv.reader
objects can easily handle this: 如果两个部分用定界符不同,则两个
csv.reader
对象可以轻松处理此问题:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.