I'm pretty new to Python - just wondering if there was a library function or easy way to truncate a file to the first 100 lines or less?
Asked
Active
Viewed 3,078 times
2 Answers
12
with open("my.file", "r+") as f:
[f.readline() for x in range(100)]
f.truncate()
EDIT A 5 % speed increase can be had by instead using the xrange iterator and not storing the entire list:
with open("my.file", "r+") as f:
for x in xrange(100):
f.readline()
f.truncate()

Lauritz V. Thaulow
- 49,139
- 12
- 73
- 92
1
Use one of the solutions here: Iterate over the lines of a string and just grab the first hundred, i.e.
import itertools
lines = itertools.islice(iter, 100)

Community
- 1
- 1

bradley.ayers
- 37,165
- 14
- 93
- 99