📅  最后修改于: 2023-12-03 15:19:07.887000             🧑  作者: Mango
有时候我们需要删除文本文件中的一些内容。在 Python 中,有几种方法可以实现这一点。本文将介绍其中的两种常见方法。
该方法涉及到以下步骤:
以下是 Python 代码片段:
def delete_lines(file_path, lines_to_delete):
with open(file_path, 'r') as file:
lines = file.readlines()
with open(file_path, 'w') as file:
for line in lines:
if line.strip() not in lines_to_delete:
file.write(line)
您可以像这样使用它:
delete_lines('example.txt', ['line2', 'line4'])
此函数将从示例.txt文件中删除包含 "line2"或"line4"的任何行。
这种方法更为安全,因为它不直接更改原始文件。它涉及以下步骤:
以下是 Python 代码片段:
import shutil
def delete_lines(file_path, lines_to_delete):
temp_file = file_path + '.temp'
with open(file_path, 'r') as file, open(temp_file, 'w') as temp:
lines = file.readlines()
for line in lines:
if line.strip() not in lines_to_delete:
temp.write(line)
shutil.move(temp_file, file_path)
您可以像这样使用它:
delete_lines('example.txt', ['line2', 'line4'])
此函数将从示例.txt文件中删除包含 "line2"或"line4"的任何行。
以上是 Python 删除文本文件中的文本的两种方法。如果您有要添加的其他提示,请在评论中分享。