2

In python when you open a file using open method it returns file object. Can we use this object to read multiple times?

If yes then why it is not working for me. I am using pyhon2.7.2 version

 from sys import argv

 script, filename = argv

 txt = open(filename)

 print "Here is your file %r" % filename
 # Reads the complete file into the txt variable
 print txt.read()
 # Here i am using txt file object again to read byte by byte of the file
 # which doesn't seem to be working.
 print txt.read(1)

any reasons why its not working?

Gaurav Parek
  • 317
  • 6
  • 20

1 Answers1

7

Sure. To move the "cursor" back to the start, do:

txt.seek(0)

Docs:

seek(offset[, whence]) -> None.  Move to new file position.

Argument offset is a byte count.  Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file).  If the file is opened in text mode,
only offsets returned by tell() are legal.  Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
shx2
  • 61,779
  • 13
  • 130
  • 153
  • @user3427746: also if you are mixing buffered and unbuffered I/O (it is not recommended) then you might need to call `file.flush()` on Python 2 to "discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application". Here's [an example](http://stackoverflow.com/a/22417159/4279) – jfs Mar 23 '14 at 12:55