[英]String won't be written to file
I have a code which I am writing 'testing' into, once the file is done I was hoping to see 'testing' in the text file but it is still empty. 我有一个代码正在写入“测试”,一旦文件完成,我希望在文本文件中看到“测试”,但它仍然为空。 Am I missing something here?
我在这里想念什么吗?
import shutil
import sys
f = open('test.txt', 'r+')
f.write('testing')
shutil.copyfileobj(f, sys.stdout)
It is actually correct, the problem is that when you write
, the buffer pointer moves, so when you copy, it won't print anything. 实际上是正确的,问题在于当您
write
,缓冲区指针会移动,因此在复制时,它不会打印任何内容。 Try with seek
before like this: 与尝试
seek
之前是这样的:
import shutil
import sys
f = open('test.txt', 'r+')
f.write('testing')
f.seek(0)
shutil.copyfileobj(f, sys.stdout)
Hope this helps! 希望这可以帮助!
you need to close the file. 您需要关闭文件。
f.close()
EDIT 编辑
try changing the name of the file, Is it still not writting: 尝试更改文件名,是否仍未写入:
f = open('test124.txt', 'a') # use the append flag so that it creates the file.
f.write('testing')
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.