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


当前回答

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

#include <fstream>

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

其他回答

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

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

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

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

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

编码快乐!

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

#include <fstream>

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

在python中:

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

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

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

这是我的方法:

使用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)

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