replace_line
函数接受文件路径、要替换的行号和新内容作为参数。它首先使用with open
语句打开文件并读取所有行。然后,它检查给定的行号是否有效,如果无效则输出错误信息并返回。如果行号有效,它将替换相应行的内容。最后,它使用with open
语句以写入模式打开文件,并将修改后的内容写入文件。
请注意,上述代码假设文件中的行号是从0开始计数的。如果你的文件行号是从1开始计数的,请在使用时相应地调整行号参数。
# -*- coding: utf-8 -*-#
def replace_line(file_path, line_number, new_content):
with open(file_path, 'r') as file:
lines = file.readlines()
if line_number < 0 or line_number >= len(lines):
print("无效的行号")
return
lines[line_number] = new_content + '\n'
with open(file_path, 'w') as file:
file.writelines(lines)
# 使用示例
file_path = 'img_to_char.txt' # 替换的txt文件路径
line_number = 28 # 要替换的行号(从0开始计数)
new_content = 'This is the new content' # 替换的新内容
replace_line(file_path, line_number, new_content)