You're not calling functions target.close
and txt.close
, instead you're simply getting their pointers. Since they are functions (or methods, to be more accurate) you need ()
after the function's name to call it: file.close()
.
That's the problem; you open the file in write mode which deletes all the content of the file. You write in the file but you never close it, so the changes are never committed and the file stays empty. Next you open it in read mode and simply read the empty file.
To commit the changes manually, use file.flush()
. Or simply close the file and it will be flushed automatically.
Also, calling target.truncate()
is useless, since it's already done automatically when opening in write
mode, as mentioned in the comments.
Edit: Also mentioned in the comments, using with
statement is quite powerful and you should use it instead. You can read more of with from http://www.python.org/dev/peps/pep-0343/, but basically when used with files, it opens the file and automatically closes it once you unindent. This way you don't have to worry about closing the file, and it looks much better when you can clearly see where the file is being used, thanks to the indentation.
Quick example:
f = open("test.txt", "r")
s = f.read()
f.close()
Can be done shorter and better looking by using with
statement:
with open("test.txt", "r") as f:
s = f.read()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…