所以我试图让我的python程序接受来自用户的文件,然后截断文件,向其添加内容,输出文件,最后关闭。问题是它不会输出。我在写入+读取模式下打开了文件,但文件不会在target.read()
上输出。这是我的源代码。问题出在底部的第三行。
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."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w+r')
print "Truncating the file. Good bye!"
target.truncate()
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 a file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And now we get to read the file."
print target.read()
print "And finally, we close it."
target.close()
我在Mac上使用终端,运行python 2.7。 这是我的输出。
We're going to erase 'test2.txt'.
If you don't want that, hit CTRL-C.
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Good bye!
Now I'm going to ask you for three lines.
line 1: asd
line 2: zxcz
line 3: qwe
I'm going to write these to a file.
And now we get to read the file.
And finally, we close it.
底部的第二行是输出应该是的位置。何时使用cat
输出文件,它具有应该的内容。请让我知道我做错了什么。
答案 0 :(得分:8)
在执行target.read()
之前,您希望通过执行以下操作seek
到文件的开头:
target.seek(0)
如果您不寻求文件的开头,文件“cursor”将位于文件的末尾,因此当您尝试阅读时,您将什么也得不到。这是因为在你写的时候,光标会前进。