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


当前回答

在python中:

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

或者,如果你已经打开了一个文件:

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

其他回答

写入和读取文件内容

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

这对我很有效

除非需要删除文件的结尾,否则不能就地“擦除”文件。要么满足于覆盖一个“空”值,要么读取文件中您关心的部分并将其写入另一个文件。

以“写”模式打开一个文件可以清除它,你不需要特别地写入它:

open("filename", "w").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都有这些函数。

你也可以使用这个(基于上面的一些答案):

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

当然,这是一种非常糟糕的清除文件的方式,因为它需要很多行代码,但我只是写这个来告诉你们,它也可以在这个方法中完成。

编码快乐!