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

python写文件追加 按行追加_python 追加写入匹配文本并追加内容

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

问题描述

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
seek 3.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'

参考文献

  1. open — Python 文档
  2. Python3 open() 函数 | 菜鸟教程
  3. open文件操作之mode模式剖析
  4. Python文件打开方式详解——a、a+、r+、w+、rb、rt
  5. python 文件混合读写模式 mode=‘r+’
  6. python下在txt指定行追加文本
  7. 如何流式读取数G超大文件
  8. Python3 seek()中间追加失败
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/183397.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • pycharm 3.2激活码 2022【在线注册码/序列号/破解码】

    pycharm 3.2激活码 2022【在线注册码/序列号/破解码】,https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • centos7安装wget命令_centos中wget

    centos7安装wget命令_centos中wget方法一:yuminstallwget方法二:由于安装的centos是mini版,并且自带的软件源里也没有wget命令,只好自己下载了。网易源下载wget的连接下载后上传到centos上,CD到安装包的目录里,使用rpm安装。rpm-ivhwget-1.14-18.el7_6.1.x86_64.rpm安装包上传到服务器上可以用三种方法上传。centos安装…

    2022年10月10日
  • 【转载】HTTP协议与WEB本质

    【转载】HTTP协议与WEB本质

    2021年11月18日
  • Android原生编解码接口 MediaCodec 之——踩坑

    Android原生编解码接口 MediaCodec 之——踩坑关键帧MediaCodec有两种方式触发输出关键帧,一是由配置时设置的KEY_FRAME_RATE和KEY_I_FRAME_INTERVAL参数自动触发,二是运行过程中通过setParameters手动触发输出关键帧。自动触发输出关键帧在MediaCodec硬编码中设置I(关键帧)时间间隔,在api中是这么设置的mediaFormat.setInteger(MediaF………

    2022年10月24日
  • 游戏数值策划

    游戏数值策划游戏数值-拆解方法篇大家好,我是Alice,一名喜欢捣腾数字的游戏数值策划12345~o(* ̄▽ ̄*)ブ工作中我会经常拆解游戏数值,通过数值理解市面上优秀游戏的设计思路。今天想在这里跟大家分享一下我研究游戏数值的流程。如果各位有什么好方法,也请在评论区留言,期待看到你的想法。我平时拆解数值的流程主要分为六个阶段:准备阶段 数据收集 分析数据规律 提出猜想 根据数据验证猜想 拆解的应用不过在介绍具体流程之前,我想和你们先聊一下,数值拆解的目的。我认为数值拆解的目的大概可以分

  • Activiti工作流使用之项目实例

    Activiti工作流使用之项目实例Activiti工作流使用之项目实例文章目录Activiti工作流使用之项目实例一、配置文件1.1pom依赖引入1.2application.properties文件二、BPMN文件三、控制层Controller四、实现类Service4.1流程启动(不进入下一环节)4.2流程启动(直接进入下一环节)4.3审批任务4.4查询我发起的流程4.5流程下任务详情4.6删除流程4.7我待审核的任务五、监听器六、流程示意一、配置文件1.1pom依赖引入<dependency>

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号