noob: print and file.read()

MRAB python at mrabarnett.plus.com
Mon Dec 3 18:31:56 EST 2012


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.
>




More information about the Python-list mailing list