我有一个文本文件,我想在Python中擦除。我怎么做呢?


当前回答

正如@jamylak所建议的,包含上下文管理器优点的一个好的替代方案是:

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

其他回答

在程序中将文件指针赋值为空只会消除对文件的引用。文件还在那里。我认为c stdio.h中的remove()函数就是你要找的。对Python不太确定。

写入和读取文件内容

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

这对我很有效

你必须覆盖这个文件。在c++中:

#include <fstream>

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

由于文本文件是顺序的,所以不能直接擦除其中的数据。你的选择是:

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.

看看seek/truncate函数/方法来实现上面的任何想法。Python和C都有这些函数。

当使用open("myfile.txt", "r+")作为my_file:时,我在myfile.txt中得到奇怪的0,特别是因为我先读取文件。为了让它工作,我必须首先用my_file.seek(0)将my_file的指针更改为文件的开头。然后我可以执行my_file.truncate()来清除文件。