Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to print the first few lines in Python from a text?

Status
Not open for further replies.

ararik

Technical User
Feb 28, 2009
1
0
0
US
Hi I am trying to read and print lines from a text.

I can print ALL the lines by typing:

myfile = open("c:/test/buffet.txt","r")
for line in myfile:
... print line

Q1. How can I print the first 10 lines?
Q2. How can I print the every other line?

Also, How does Python define a line? How does it define a string?

I also used the following command, which seemed to work but gave me different results

myfile = open("c:/test/buffet.txt","r").readlines() [:10]
print myfile

For printing the first 10 lines, the result was different depending on how the text file was editted... That is, if I combined all the sentences together as a pragraph, it differred from the one that I wrote each sentence seperately as a line. That's why I asked how it defines lines.

Thank you.
 
arik said:
For printing the first 10 lines, the result was different depending on how the text file was editted... That is, if I combined all the sentences together as a pragraph, it differred from the one that I wrote each sentence seperately as a line.

A line have nothing to do with a sentence. The line is limited with a special newline-character "\n".

I would suggest, that you first read about some basics how to process text files - e.g. this chapter Handling Files from the book by Alan Gauld Learning to Program
 
If you really want sentences, you can read in either the whole file or enough bytes to ensure you have all you want, then split on '.' and print the first n elements of the resultant list.

_________________
Bob Rashkin
 
ararik said:
Also, How does Python define a line?
Hitting the Enter key in your text editor starts a new line. If you type a long paragraph in a text editor and never hit the Enter key, then that paragraph is all on one line.

Your text editor may display the paragraph as being on multiple screen lines (a feature called word-wrap), but that's a function of your editor and has nothing to do with the actual contents of the file, which is all Python can see.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top