Read A File Starting From The Second Line In Python
Solution 1:
You should be able to call next
and discard the first line:
withopen('filename') as fin:
next(fin) # cast into oblivionfor line in fin:
... # do something
This is simple and easy because of the nature of fin
, being a generator.
Solution 2:
withopen("filename", "rb") as fin:
print(fin.readlines()[1:])
Solution 3:
Looking at the documentation for islice
itertools.islice(iterable, stop) itertools.islice(iterable, start, stop[, step])
Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line).
I think you can just tell it to start at the second line and iterate until the end. e.g.
withopen('filename') as fin:
for line in islice(fin, 2, None): # <--- change 1 to 2 and 16 to Noneprint line
Post a Comment for "Read A File Starting From The Second Line In Python"