This will do it.
with open('file_in.txt') as f:
for numb,line in enumerate(f, 1):
if 1 <= numb <= 150:
print line
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
Another way is
from itertools import islice
with open(filename) as lines:
for line in islice(lines, 0, 150):
# ...
When you want to write [:150] and you can't, use islice(., 0, 150), that's the trick.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
Thanks, it worked! (I used the first solution in order not to import another library to my script).
What if I have to read a file which is online?
Let's say that I have a file like
text.txt
"hello world!"
and this file is in
http://url.to.file.com/subfolder/text.txt
How can I grab and use the text "hello world!" in my script?
Thanks again
You have to use urllib2
fileobj = urllib2.urlopen("http://url.to.file.com/subfolder/text.txt")
You can also use urllib.urlretrieve() to download the file locally first.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691