求助:如何用Python 3修改文本文件中行首为2的行的末尾内容
Python3实现指定文本行修改
以下是实现需求的代码及说明:
实现步骤
- 读取目标文本文件的所有内容
- 逐行检查:若行首字符为
2,将该行最后两个字符替换为12 - 将处理后的内容重新写入原文件
完整代码
# 定义文件名 file_name = "data.txt" processed_lines = [] # 读取文件并处理每行 with open(file_name, 'r', encoding='utf-8') as input_file: for line in input_file: # 记录行是否包含换行符 has_newline = line.endswith('\n') # 去除换行符处理内容 content = line.rstrip('\n') if content.startswith('2'): # 替换最后两个字符为12 content = content[:-2] + '12' # 恢复换行状态并加入结果列表 if has_newline: processed_lines.append(content + '\n') else: processed_lines.append(content) # 将处理后的内容写入文件 with open(file_name, 'w', encoding='utf-8') as output_file: output_file.writelines(processed_lines)
代码说明
- 使用
with语句操作文件,无需手动关闭文件,避免资源泄漏 - 保留原始行的换行状态,避免处理后出现多余空行或丢失换行
- 通过字符串切片
[:-2]快速获取除最后两个字符外的内容,拼接12完成替换 - 最后用
writelines批量写入处理后的行,比逐行写入效率更高
内容的提问来源于stack exchange,提问作者HOUND_OP
相关产品推荐
相关产品推荐

