我有一个文本文件想要在Python中删除。该怎么做?
open('file.txt', 'w').close()
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
#include<fstream>
和std::ofstream("file.txt");
大致与Python中的长度相同。:) - wilhelmtellf.seek(0)
将文件指针移动到文件开头。 - Johan Engblomf.truncate(0)
后添加 f.seek(0)
,否则文件开头会出现奇怪的 \x00 字符。 - krishna chaitanya以“写”模式打开文件会将其清空,您不必专门写入它:
open("filename", "w").close()
你应该关闭它,因为文件自动关闭的时间可能是实现特定的。
并非完整答案,更像是对ondra答案的扩展
在使用truncate()
(我偏爱的方法)时,请确保光标位于所需位置。
当打开一个新文件进行读取 - open('FILE_NAME','r')
默认情况下其光标位置为0。
但如果您已经在代码中解析了该文件,请务必再次将其指向文件开头,即 truncate(0)
默认情况下,truncate()
从当前光标位置开始截断文件内容。
truncate()
如何与光标位置相关工作非常有帮助。 - Frankstar正如@jamylak所建议的那样,包括上下文管理器好处的一个很好的替代方案是:Benefits of context managers
with open('filename.txt', 'w'):
pass
with open("myfile.txt", "r+") as my_file:
时,我在读取文件之前就在myfile.txt
中得到了奇怪的零值。为了使其正常工作,我必须先使用 my_file.seek(0)
将指针移动到文件的开头,然后才能使用my_file.truncate()
清空文件。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)
文件内容的读写
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();
close()
。析构函数会关闭文件。所以你只需要创建一个临时的:ofstream("test.txt");
- wilhelmtellfile = open('filename.txt', 'w')
file.close()
当然,这种清除文件的方法非常糟糕,因为它需要很多代码行,但我只是为了向你展示这种方法而编写的。
祝编码愉快!
这是我的方法:
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)
由于我们使用了with open
,文件将会自动关闭。
open('file.txt', 'w').close()
看起来很奇怪,但是它是有效的。 - Charlie Parker