在使用之前,您需要将文件光标移回文件开头read()
。
In [14]: target=open("data.txt","w+")
In [15]: target.write("foo bar")
In [21]: target.tell() #current position of the cursor
Out[21]: 7L
In [16]: target.seek(0) #change it to 0
In [17]: target.read()
Out[17]: 'foo bar'
帮助seek()
:
In [18]: print target.seek.__doc__
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.
帮助tell()
:
In [22]: print target.tell.__doc__
tell() -> current file position, an integer (may be a long integer).