[英]How to erase the file contents of text file in Python?
我在 Python 中有我想刪除的文本文件。我該怎么做?
在蟒蛇中:
open('file.txt', 'w').close()
或者,如果您已經打開了一個文件:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
不是一個完整的答案,更多的是對 ondra 答案的擴展
使用truncate()
(我的首選方法)時,請確保光標位於所需位置。 當打開一個新文件進行讀取時 - open('FILE_NAME','r')
默認情況下,它的光標位於 0。 但是,如果您在代碼中解析了文件,請確保再次指向文件的開頭,即truncate(0)
默認情況下, truncate()
從當前光標位置開始截斷文件的內容。
在“寫入”模式下打開文件會將其清除,您不必專門寫入:
open("filename", "w").close()
(您應該關閉它,因為文件自動關閉的時間可能是特定於實現的)
當使用with open("myfile.txt", "r+") as my_file:
,我在myfile.txt
得到奇怪的零,特別是因為我首先讀取文件。 為了讓它工作,我必須首先使用my_file.seek(0)
將my_file
的指針更改為文件的開頭。 然后我可以執行my_file.truncate()
來清除文件。
來自用戶@jamylak 的另一種形式open("filename","w").close()
是
with open('filename.txt','w'): pass
您必須覆蓋該文件。 在 C++ 中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
如果安全性對您很重要,那么打開文件進行寫入並再次關閉它是不夠的。 至少一些信息仍將保留在存儲設備上,並且可以通過例如使用光盤恢復實用程序找到。
例如,假設您正在擦除的文件包含生產密碼,需要在當前操作完成后立即刪除。
使用完文件后將其填零有助於確保敏感信息被銷毀。
在最近的一個項目中,我們使用了以下代碼,它適用於小文本文件。 它用零行覆蓋現有內容。
import os
def destroy_password_file(password_filename):
with open(password_filename) as password_file:
text = password_file.read()
lentext = len(text)
zero_fill_line_length = 40
zero_fill = ['0' * zero_fill_line_length
for _
in range(lentext // zero_fill_line_length + 1)]
zero_fill = os.linesep.join(zero_fill)
with open(password_filename, 'w') as password_file:
password_file.write(zero_fill)
請注意,填零並不能保證您的安全。 如果您真的很擔心,最好進行零填充並使用像File Shredder或CCleaner這樣的專業實用程序來清除驅動器上的“空”空間。
寫入和讀取文件內容
def writeTempFile(text = None):
filePath = "/temp/file1.txt"
if not text: # If not provided return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
它對我有用
您也可以使用它(基於上面的一些答案):
file = open('filename.txt', 'w')
file.close()
當然,這是一種非常糟糕的清除文件的方法,因為它需要這么多行代碼,但我寫這個只是為了向您展示也可以用這種方法完成。
快樂編碼!
由於文本文件是連續的,您不能直接擦除其中的數據。 您的選擇是:
查看seek
/ truncate
函數/方法來實現上述任何想法。 Python 和 C 都有這些功能。
除非您需要擦除結尾,否則您無法就地“擦除”文件。 要么滿足於覆蓋“空”值,要么讀取您關心的文件部分並將其寫入另一個文件。
在您的程序中將文件指針分配為 null 只會擺脫對文件的引用。 文件還在。 我認為 c stdio.h
的remove()
函數正是您在那里尋找的。 不確定 Python。
這是我的方法:
r+
模式打開文件file.read()
從文件中讀取當前數據file.seek(0)
將指針移動到第一行file.truncate(0)
從文件中刪除舊數據file.read()
保存的內容所以完整的代碼將如下所示:
with open(file_name, 'r+') as file:
old_data = file.read()
file.seek(0)
file.truncate(0)
file.write('my new content\n')
file.write(old_data)
因為我們使用with open
,文件會自動關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.