大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新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'
参考文献
- open — Python 文档
- Python3 open() 函数 | 菜鸟教程
- open文件操作之mode模式剖析
- Python文件打开方式详解——a、a+、r+、w+、rb、rt
- python 文件混合读写模式 mode=‘r+’
- python下在txt指定行追加文本
- 如何流式读取数G超大文件
- Python3 seek()中间追加失败
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/183397.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...