可以使用同一个文件对象多次读取文件吗?

Gau*_*rek 2 python-2.7

在Python中,当您使用open方法打开文件时,它会返回文件对象。我们可以使用这个对象来多次读取吗?

如果是,那么为什么它对我不起作用。我使用的是pyhon2.7.2版本

 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)
Run Code Online (Sandbox Code Playgroud)

它不工作的任何原因?

shx*_*hx2 7

当然。要将“光标”移回到开头,请执行以下操作:

txt.seek(0)
Run Code Online (Sandbox Code Playgroud)

文件:

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.
Run Code Online (Sandbox Code Playgroud)