Re: noob: print and file.read()

Discussion in 'Python' started by MRAB, Dec 3, 2012.

  1. MRAB

    MRAB Guest

    On 2012-12-03 23:06, Andrew Z wrote:
    > Hello,
    > why the following code doesn't print the content of the file:
    > #!/usr/bin/python
    >
    > from_file ="file.txt"
    > in_file = open(from_file)
    > str = in_file.read()


    You've read the entire file, leaving the file pointer positioned at the
    end of the file.

    > print "Here should be the output from the file - ", in_file.read()


    You're trying to read the file again, but the file pointer is still
    positioned at the end of the file, and there's no more left to read.

    If you want to read it again, you'll need to reset the file pointer
    back to the start of the file using in_file.seek(0).

    > print "Here should be the output from the STR- ", str
    > in_file.close()
    >
    >
    > The first "print" has nothing whereas the second properly displays the
    > content of the file.
    >
     
    MRAB, Dec 3, 2012
    #1
    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. keto
    Replies:
    0
    Views:
    1,018
  2. David Cournapeau

    print a vs print '%s' % a vs print '%f' a

    David Cournapeau, Dec 30, 2008, in forum: Python
    Replies:
    0
    Views:
    386
    David Cournapeau
    Dec 30, 2008
  3. Replies:
    3
    Views:
    123
    Brian Candler
    Dec 25, 2008
  4. Alex Dowad
    Replies:
    4
    Views:
    299
    Michel Demazure
    May 1, 2010
  5. Andrew Z

    noob: print and file.read()

    Andrew Z, Dec 3, 2012, in forum: Python
    Replies:
    0
    Views:
    192
    Andrew Z
    Dec 3, 2012
Loading...

Share This Page