2 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
首先要了解的是,當(dāng)您執(zhí)行 textFile.write 時(shí),不確定是否會(huì)立即寫入文件。這是為了通過將數(shù)據(jù)首先放入緩沖區(qū)來提高寫入效率,只有當(dāng)緩沖區(qū)已滿或調(diào)用刷新或文件關(guān)閉(內(nèi)部執(zhí)行刷新)時(shí),緩沖區(qū)才會(huì)寫入文件。
所以原因是不適用于兩個(gè)不同的變量名稱是因?yàn)閷懖僮鲝奈凑嬲l(fā)生在該行之前textFile_1.close()
它使用相同變量名“工作”的原因是,當(dāng)您重新綁定textFile = open(filename)
以前綁定到的文件時(shí)textFile
,現(xiàn)在沒有在任何地方引用它,因此垃圾收集器將其刪除。當(dāng)文件句柄被刪除時(shí),數(shù)據(jù)被寫入文件,因此您可以在之后讀取它。
另外,在處理文件時(shí)應(yīng)該使用 with open 習(xí)慣用法:
見下文,F(xiàn)ileDebug 包裝器向您顯示文件何時(shí)被刪除以及數(shù)據(jù)何時(shí)被寫入。
class FileDebug:
? ? def __init__(self, f, name):
? ? ? ? self.f = f
? ? ? ? self.name = name
? ? def close(self):
? ? ? ? print(f"Closing file (var: {self.name})")
? ? ? ? self.f.close()
? ? def write(self, *args, **kwargs):
? ? ? ? self.f.write(*args, **kwargs)
? ? def read(self, *args, **kwargs):
? ? ? ? return self.f.read(*args, **kwargs)
? ? def __del__(self):
? ? ? ? print(f"Del completed (var: {self.name})")
filename = "text.txt"
def different_name():
? ? textCont = "Hello World"
? ? print("Original content of the file")
? ? print(FileDebug(open(filename), "No name").read())
? ? textFile = FileDebug(open(filename, "w"), "textFile")
? ? textFile.write(textCont)
? ? print("New file content:")
? ? textFile_1 = FileDebug(open(filename), "textFile_1")
? ? print(textFile_1.read())
? ? textFile.close()
? ? textFile_1.close()
def same_name():
? ? textCont = "Hello World"
? ? print("Original content of the file")
? ? print(FileDebug(open(filename), "No name").read())
? ? textFile = FileDebug(open(filename, "w"), "textFile")
? ? textFile.write(textCont)
? ? print("New file content:")
? ? textFile = FileDebug(open(filename), "textFile")
? ? print(textFile.read())
? ? textFile.close()
different_name()
"""
Original content of the file
Del completed (var: No name)
New file content:
Closing file (var: textFile)
Closing file (var: textFile_1)
Del completed (var: textFile)
Del completed (var: textFile_1)
"""
#same_name()
"""
Original content of the file
Del completed (var: No name)
New file content:
Del completed (var: textFile) # the file is closed and the data is written
Hello World
Closing file (var: textFile)
Del completed (var: textFile)
"""

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
第二個(gè)案例中的問題得到了解決。
解決方案是在寫入之后但再次讀取之前關(guān)閉文件。
print(open(filename).read())
textFile = open(filename, "w")
textFile.write(textCont)
textFile.close() // close the file from write mode before reading it again
print("your file content:")
textFile_1 = open(filename)
print(textFile_1.read())
textFile_1.close()
添加回答
舉報(bào)