[英]String won't be written to file
我有一個代碼正在寫入“測試”,一旦文件完成,我希望在文本文件中看到“測試”,但它仍然為空。 我在這里想念什么嗎?
import shutil
import sys
f = open('test.txt', 'r+')
f.write('testing')
shutil.copyfileobj(f, sys.stdout)
實際上是正確的,問題在於當您write
,緩沖區指針會移動,因此在復制時,它不會打印任何內容。 與嘗試seek
之前是這樣的:
import shutil
import sys
f = open('test.txt', 'r+')
f.write('testing')
f.seek(0)
shutil.copyfileobj(f, sys.stdout)
希望這可以幫助!
您需要關閉文件。
f.close()
編輯
嘗試更改文件名,是否仍未寫入:
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.