我有一个文本文件,我想在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)

因为我们使用的是打开,文件会自动关闭。

其他回答

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

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

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

编码快乐!

写入和读取文件内容

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

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

这不是一个完整的答案,更多的是对ondra答案的延伸

当使用truncate()(我的首选方法)时,确保您的光标位于所需的位置。 当打开一个新文件进行读取时- open('FILE_NAME','r'),它的光标默认为0。 但如果你在代码中解析了文件,请确保再次指向文件的开头,即truncate(0) 默认情况下,truncate()从当前cusror位置开始截断文件的内容。

一个简单的例子