read a file line by line using readline()

Discussion in 'Python' started by Phoe6, Mar 22, 2006.

  1. Phoe6

    Phoe6 Guest

    Hi all,
    I just read the manual and got to know I can use a for loop to iterate
    through the lines in the file.

    But so far, I was strugling with the following:

    import os
    file = open('File1.txt','r')
    line = file.readline()
    while line !=' ':
    print line
    line = file.readline()

    As mentioned in the docs, the EOF returns an empty string. I am unable
    to catch or match against the EOF. Please help me in pointing out as
    where I am making the mistake.


    --
    Senthil
    http://phoe6.livejournal.com
    Phoe6, Mar 22, 2006
    #1
    1. Advertising

  2. Phoe6

    Thomas Girod Guest

    If your code is exactly what you've copy-pasted, then you are not
    testing against an empty string but a "one blank space" string ...

    I've just tried with :

    while line != "":

    and it works very well.
    Thomas Girod, Mar 22, 2006
    #2
    1. Advertising

  3. Phoe6

    Phoe6 Guest

    Thomas Girod wrote:
    >
    > while line != "":
    >
    > and it works very well.


    Thanks Thomas, I stand corrected now.
    my mistake, I was checking against a single space ' ' instead of empty
    string ''. :(

    --
    Senthil
    Phoe6, Mar 22, 2006
    #3
  4. Phoe6 a écrit :
    > Hi all,
    > I just read the manual and got to know I can use a for loop to iterate
    > through the lines in the file.
    >
    > But so far, I was strugling with the following:
    >
    > import os
    > file = open('File1.txt','r')


    'file' is the builtin type for file objects (like the one returned by
    open()). Avoid using it as an identifier, this shadows the file type.

    > line = file.readline()
    > while line !=' ':


    As Thomas pointed out, this is not an empty string !-)

    Also, this is not a for loop...

    > print line
    > line = file.readline()


    Do yourself a favor, use a for loop. Also, a file opened in read mode is
    already an iterator :

    f = open('path/to/file')
    for line in f:
    do_something_with(line)
    f.close()
    Bruno Desthuilliers, Mar 23, 2006
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hugo
    Replies:
    10
    Views:
    1,299
    Matt Humphrey
    Oct 18, 2004
  2. scad
    Replies:
    23
    Views:
    1,157
    Alf P. Steinbach
    May 17, 2009
  3. gavino
    Replies:
    4
    Views:
    535
    gavino
    Sep 20, 2010
  4. Jean-Michel
    Replies:
    0
    Views:
    359
    Jean-Michel
    Dec 22, 2007
  5. Andrew DeFaria
    Replies:
    1
    Views:
    208
    Ben Morrow
    Jan 30, 2008
Loading...

Share This Page