1

嘿!我的脚本有问题。

我是在阅读LPTHW 的书时写的。

我没有收到错误消息,但没有得到正确的输出,我认为我的系统可能存在设置错误。我很困惑。

这是脚本:

from sys import argv

script, filename = argv


print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w+')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1= raw_input("line1: ")
line2= raw_input("line2: ")
line3= raw_input("line3: ")

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

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "Now, I am going to read the file"
print target.read()

print "And finally, we close it."
target.close()

这是输出:

PS C:\Users\Isaac\lpthw> python ex1.py sample.txt
We're going to erase 'sample.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line1: i
line2: love
line3: mo
I'm going to write these to the file.
Now, I am going to read the file
#☻    ` ▬☻    ` ▬☻      .☻
4

1 回答 1

6

当您调用target.write()时,文件指针就在写入数据之后。你可以打电话target.tell()看看它在哪里:

>>> target.tell()
0
>>> target.write('hello')
>>> target.tell()
5

在阅读文件之前,您需要先找到文件的开头:

target.seek(0)
print target.read()
于 2012-08-24T05:07:53.310 回答