-1

我对本练习中的额外学分有疑问。我希望这个脚本不仅可以打开并写入文件,还可以将我刚刚写入文件的内容读回给我。在 print target.read() 部分,控制台打印一堆空白空间,但不是我输入的文字。文件的写入部分有效,因为当我打开实际的 .txt 文件时,文本就在那里。所有额外的空白空间来自哪里?为什么它不给我读回文本?谢谢!

print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write("%s\n%s\n%s\n" %(line1, line2, line3))

print target.read()
4

1 回答 1

4

在使用之前,您需要将文件光标移回文件开头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).
于 2013-01-10T07:21:55.750 回答