我对此练习中的额外学分有疑问。我希望这个脚本不仅可以打开和写入文件,还可以将我刚写入文件的内容读回给我。在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()
答案 0 :(得分: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).