在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)
为什么它不起作用的原因?
答案 0 :(得分:3)
不确定。移动"光标"回到开头,做:
txt.seek(0)
文档:
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.