We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,924 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

selected lines from textfile

Hi there,
how can I read a file line by line till the 150th line?
I mean, I know the

for line in f:

but I want to read only (let's say) 150 lines of the f file.

Thanks a lot

3
Contributors
5
Replies
15 Hours
Discussion Span
1 Year Ago
Last Updated
6
Views
giancan
Junior Poster in Training
61 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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
Posting Shark
956 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

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
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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

giancan
Junior Poster in Training
61 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

Thanks again!

giancan
Junior Poster in Training
61 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0991 seconds using 2.66MB