以下是一个示例代码,可以清除特定文本文件行的内容,而不删除换行符:
def clear_specific_lines(file_path, target_lines):
# 读取文件内容
with open(file_path, 'r') as file:
lines = file.readlines()
# 清除特定行的内容
for line_number in target_lines:
if line_number < len(lines):
lines[line_number] = '' # 将目标行的内容设为空字符串
# 将修改后的内容写回文件
with open(file_path, 'w') as file:
file.writelines(lines)
# 示例使用
file_path = 'example.txt' # 文件路径
target_lines = [1, 3] # 要清除内容的行号列表
clear_specific_lines(file_path, target_lines)
上述示例代码中,clear_specific_lines
函数接受两个参数:文件路径 file_path
和要清除内容的行号列表 target_lines
。函数首先使用 open
函数以只读模式打开文件,并使用 readlines
方法读取文件的所有行。然后,使用循环遍历 target_lines
中的行号,如果该行号小于文件行数,则将该行的内容设为空字符串。最后,使用 open
函数以写入模式打开文件,并使用 writelines
方法将修改后的内容写回文件。
请注意,该示例代码假设文件存在且行号从0开始计数。如果要处理的文件不存在,或者行号超出了文件的实际行数,可能会引发异常。因此,在实际使用时,请根据需要进行适当的错误处理。