python写文件追加 按行追加_python 追加写入

python写文件追加 按行追加_python 追加写入文章目录 问题描述 1 读进列表后覆盖原文件 2 FileInput 类 3 seek 对比 遇到的坑 参考文献 问题描述 Python 匹配文本并在其上一行追加文本 test txt a b c d e 1 读进列表后覆盖原文件 def match then insert filename match content 匹配后在该行追加 param filename

文章目录

问题描述

1.读进列表后覆盖原文件

2.FileInput类

3.seek

对比

遇到的坑

参考文献

问题描述

Python匹配文本并在其上一行追加文本

test.txt

a
b
c
d
e

1.读进列表后覆盖原文件

def match_then_insert(filename, match, content):
"""匹配后在该行追加 :param filename: 要操作的文件 :param match: 匹配内容 :param content: 追加内容 """
lines = open(filename).read().splitlines()
index = lines.index(match)
lines.insert(index, content)
open(filename, mode='w').write('\n'.join(lines))


match_then_insert('test.txt', match='c', content='123')

效果

a
b
123
c
d
e

2.FileInput类

from fileinput import FileInput


def match_then_insert(filename, match, content):
"""匹配后在该行追加 :param filename: 要操作的文件 :param match: 匹配内容 :param content: 追加内容 """
for line in FileInput(filename, inplace=True): # 原地过滤
if match in line:
line = content + '\n' + line
print(line, end='') # 输出重定向到原文件


match_then_insert('test.txt', match='c', content='123')

3.seek

def match_then_insert(filename, match, content):
"""匹配后在该行追加 :param filename: 要操作的文件 :param match: 匹配内容 :param content: 追加内容 """
with open(filename, mode='rb+') as f:
while True:
try:
line = f.readline() # 逐行读取
except IndexError: # 超出范围则退出
break
line_str = line.decode().splitlines()[0]
if line_str == match:
f.seek(-len(line), 1) # 光标移动到上一行
rest = f.read() # 读取余下内容
f.seek(-len(rest), 1) # 光标移动回原位置
f.truncate() # 删除余下内容
content = content + '\n'
f.write(content.encode()) # 插入指定内容
f.write(rest) # 还原余下内容
break
match_then_insert('test.txt', match='c', content='123')

对比

方案耗时/s
读进列表后覆盖原文件54.42
FileInput类121.59
seek3.53
from timeit import timeit
from fileinput import FileInput
def init_txt():
open('test.txt', mode='w').write('\n'.join(['a', 'b', 'c', 'd', 'e']))
def f1(filename='test.txt', match='c', content='123'):
lines = open(filename).read().splitlines()
index = lines.index(match)
lines.insert(index, content)
open(filename, mode='w').write('\n'.join(lines))
def f2(filename='test.txt', match='c', content='123'):
for line in FileInput(filename, inplace=True):
if match in line:
line = content + '\n' + line
print(line, end='')
def f3(filename='test.txt', match='c', content='123'):
with open(filename, mode='rb+') as f:
while True:
try:
line = f.readline()
except IndexError:
break
line_str = line.decode().splitlines()[0]
if line_str == match:
f.seek(-len(line), 1)
rest = f.read()
f.seek(-len(rest), 1)
f.truncate()
content = content + '\n'
f.write(content.encode())
f.write(rest)
break
init_txt()
print(timeit(f1, number=1000))
init_txt()
print(timeit(f2, number=1000))
init_txt()
print(timeit(f3, number=1000))

遇到的坑

报错可试试在文件头部添加

# -*- coding: utf-8 -*-

或指定 encoding='utf-8'

参考文献

open — Python 文档

Python3 open() 函数 | 菜鸟教程

open文件操作之mode模式剖析

Python文件打开方式详解——a、a+、r+、w+、rb、rt

python 文件混合读写模式 mode=‘r+’

python下在txt指定行追加文本

如何流式读取数G超大文件

Python3 seek()中间追加失败

编程小号
上一篇 2025-06-02 08:11
下一篇 2025-06-29 15:27

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/139468.html