[英]Does python close automatically opened file some times
我正在使用python 3.7(在Windows 10上)在終端上執行以下行。
open('textfile.txt')
在我嘗試刪除文件('textfile.txt')之后,操作系統說它正在被某些程序使用。 我關閉終端並打開一個新終端,然后執行以下代碼
open('textfile.txt').read()
我嘗試刪除文件('textfile.txt'),然后將其刪除。 我的問題是兩次都沒有將文件對象分配給任何變量,但是第一次文件沒有第二次自動關閉。
為什么第二次python自動關閉文件?
如果打開文件,則必須關閉
f = open('textfile.txt')
f.close()
或使用pythonic方式:
with open("textfile.txt") as f:
d = f.read()
#On exit with code indent it will close
print("Here the file is closed automatically")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.