喂!我的脚本出现了问题。
我在阅读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
#☻ ` ▬☻ ` ▬☻ .☻
答案 0 :(得分:6)
当你调用target.write()
时,文件指针就在写入数据之后。您可以致电target.tell()
查看它的位置:
>>> target.tell()
0
>>> target.write('hello')
>>> target.tell()
5
在阅读之前,您需要寻找文件的开头:
target.seek(0)
print target.read()