简体   繁体   English

如何擦除Python中文本文件的文件内容?

[英]How to erase the file contents of text file in Python?

I have text file which I want to erase in Python. How do I do that?我在 Python 中有我想删除的文本文件。我该怎么做?

In python:在蟒蛇中:

open('file.txt', 'w').close()

Or alternatively, if you have already an opened file:或者,如果您已经打开了一个文件:

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+

Not a complete answer more of an extension to ondra's answer不是一个完整的答案,更多的是对 ondra 答案的扩展

When using truncate() ( my preferred method ) make sure your cursor is at the required position.使用truncate() (我的首选方法)时,请确保光标位于所需位置。 When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default.当打开一个新文件进行读取时 - open('FILE_NAME','r')默认情况下,它的光标位于 0。 But if you have parsed the file within your code, make sure to point at the beginning of the file again ie truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.但是,如果您在代码中解析了文件,请确保再次指向文件的开头,即truncate(0)默认情况下, truncate()从当前光标位置开始截断文件的内容。

A simple example一个简单的例子

Opening a file in "write" mode clears it, you don't specifically have to write to it:在“写入”模式下打开文件会将其清除,您不必专门写入:

open("filename", "w").close()

(you should close it as the timing of when the file gets closed automatically may be implementation specific) (您应该关闭它,因为文件自动关闭的时间可能是特定于实现的)

When using with open("myfile.txt", "r+") as my_file: , I get strange zeros in myfile.txt , especially since I am reading the file first.当使用with open("myfile.txt", "r+") as my_file: ,我在myfile.txt得到奇怪的零,特别是因为我首先读取文件。 For it to work, I had to first change the pointer of my_file to the beginning of the file with my_file.seek(0) .为了让它工作,我必须首先使用my_file.seek(0)my_file的指针更改为文件的开头。 Then I could do my_file.truncate() to clear the file.然后我可以执行my_file.truncate()来清除文件。

来自用户@jamylak 的另一种形式open("filename","w").close()

with open('filename.txt','w'): pass

You have to overwrite the file.您必须覆盖该文件。 In C++:在 C++ 中:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

If security is important to you then opening the file for writing and closing it again will not be enough.如果安全性对您很重要,那么打开文件进行写入并再次关闭它是不够的。 At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.至少一些信息仍将保留在存储设备上,并且可以通过例如使用光盘恢复实用程序找到。

Suppose, for example, the file you're erasing contains production passwords and needs to be deleted immediately after the present operation is complete.例如,假设您正在擦除的文件包含生产密码,需要在当前操作完成后立即删除。

Zero-filling the file once you've finished using it helps ensure the sensitive information is destroyed.使用完文件后将其填零有助于确保敏感信息被销毁。

On a recent project we used the following code, which works well for small text files.在最近的一个项目中,我们使用了以下代码,它适用于小文本文件。 It overwrites the existing contents with lines of zeros.它用零行覆盖现有内容。

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)

Note that zero-filling will not guarantee your security.请注意,填零并不能保证您的安全。 If you're really concerned, you'd be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the 'empty' space on your drive.如果您真的很担心,最好进行零填充使用像File ShredderCCleaner这样的专业实用程序来清除驱动器上的“空”空间。

Writing and Reading file content写入和读取文件内容

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

It Worked for me它对我有用

You can also use this (based on a few of the above answers):您也可以使用它(基于上面的一些答案):

file = open('filename.txt', 'w')
file.close()

of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.当然,这是一种非常糟糕的清除文件的方法,因为它需要这么多行代码,但我写这个只是为了向您展示也可以用这种方法完成。

happy coding!快乐编码!

Since text files are sequential, you can't directly erase data on them.由于文本文件是连续的,您不能直接擦除其中的数据。 Your options are:您的选择是:

  • The most common way is to create a new file.最常见的方法是创建一个新文件。 Read from the original file and write everything on the new file, except the part you want to erase.从原始文件中读取并将所有内容写入新文件,除了要擦除的部分。 When all the file has been written, delete the old file and rename the new file so it has the original name.写入所有文件后,删除旧文件并重命名新文件,使其具有原始名称。
  • You can also truncate and rewrite the entire file from the point you want to change onwards.您还可以从要更改的点开始截断和重写整个文件。 Seek to point you want to change, and read the rest of file to memory.寻找要更改的点,并将文件的其余部分读入内存。 Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.找回原点,截断文件,将内容写回,没有要擦除的部分。
  • Another simple option is to overwrite the data with another data of same length.另一个简单的选择是用另一个相同长度的数据覆盖数据。 For that, seek to the exact position and write the new data.为此,寻找确切位置并写入新数据。 The limitation is that it must have exact same length.限制是它必须具有完全相同的长度。

Look at the seek / truncate function/method to implement any of the ideas above.查看seek / truncate函数/方法来实现上述任何想法。 Both Python and C have those functions. Python 和 C 都有这些功能。

You cannot "erase" from a file in-place unless you need to erase the end.除非您需要擦除结尾,否则您无法就地“擦除”文件。 Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.要么满足于覆盖“空”值,要么读取您关心的文件部分并将其写入另一个文件。

Assigning the file pointer to null inside your program will just get rid of that reference to the file.在您的程序中将文件指针分配为 null 只会摆脱对文件的引用。 The file's still there.文件还在。 I think the remove() function in the c stdio.h is what you're looking for there.我认为 c stdio.hremove()函数正是您在那里寻找的。 Not sure about Python.不确定 Python。

This is my method:这是我的方法:

  1. open the file using r+ mode使用r+模式打开文件
  2. read current data from the file using file.read()使用file.read()从文件中读取当前数据
  3. move the pointer to the first line using file.seek(0)使用file.seek(0)将指针移动到第一行
  4. remove old data from the file using file.truncate(0)使用file.truncate(0)从文件中删除旧数据
  5. write new content and then content that we saved using file.read()写入新内容,然后写入我们使用file.read()保存的内容

So full code will look like this:所以完整的代码将如下所示:

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)

Because we are using with open , file will automatically close.因为我们使用with open ,文件会自动关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM