-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 に答える