亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在python中第二次讀取文件時出現問題

在python中第二次讀取文件時出現問題

瀟湘沐 2023-04-18 15:48:42
我有點困惑為什么下面的代碼片段在第二次讀取同一個文件時返回正確的輸出:textCont = "Hello World"print("Original content of the file")print(open(filename).read())textFile = open(filename, "w")textFile.write(textCont)print("New file content:")textFile = open(filename)print(textFile.read())textFile.close()其中filename是包含一些現有數據的文件。該文件將被讀取、覆蓋,然后再次讀取。在上面的例子中,同一個變量被用于以寫入模式打開文件,然后以讀取模式打開文件。這工作正常并在第二次讀取時提供正確的輸出(顯示已覆蓋前一個的內容)但是以下版本的代碼不起作用:textCont = "Hello World"print("Original content of the file")print(open(filename).read())textFile = open(filename, "w")textFile.write(textCont)print("New file content:")textFile_1 = open(filename)print(textFile_1.read())textFile.close()textFile_1.close()當第二次使用用于以寫入模式打開文件的變量以外的變量完成讀取時,它返回一個空字符串。我知道當第二次讀取同一個文件時,它返回一個空字符串。但是為什么第一種情況下的代碼返回正確的輸出呢?誰能對此提供適當的解釋?
查看完整描述

2 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

首先要了解的是,當您執行 textFile.write 時,不確定是否會立即寫入文件。這是為了通過將數據首先放入緩沖區來提高寫入效率,只有當緩沖區已滿或調用刷新或文件關閉(內部執行刷新)時,緩沖區才會寫入文件。

所以原因是不適用于兩個不同的變量名稱是因為寫操作從未真正發生在該行之前textFile_1.close()

它使用相同變量名“工作”的原因是,當您重新綁定textFile = open(filename)以前綁定到的文件時textFile,現在沒有在任何地方引用它,因此垃圾收集器將其刪除。當文件句柄被刪除時,數據被寫入文件,因此您可以在之后讀取它。

另外,在處理文件時應該使用 with open 習慣用法:

見下文,FileDebug 包裝器向您顯示文件何時被刪除以及數據何時被寫入。

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)

"""


查看完整回答
反對 回復 2023-04-18
?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

第二個案例中的問題得到了解決。


解決方案是在寫入之后但再次讀取之前關閉文件。


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()


查看完整回答
反對 回復 2023-04-18
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號