如何使用python将字符串附加到文件中间的一行

如何使用python将字符串附加到文件中间的一行

本文介绍了如何使用python将字符串附加到文件中间的一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够打开一个文件,找到一个特定的字符串,然后将一个字符串附加到该特定行.

I want to be able to open a file, locate a specific string and then append a string to that specific line.

到目前为止,我有:

import errno
import glob

path = '/path/to/key_files/*.txt'
SubjectName = 'predetermined'

files = glob.glob(path)
for filename in files:
    try:
        with open(filename, 'r+') as f:
           for line in f:
               if SubjectName in line:
                   print(line)
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

从包含我指定的字符串的文本文件中打印一行,所以我知道所有代码都可以找到正确的行.我现在想将字符串 ',--processed\n' 添加到定位行的末尾,而不是将其附加到文件的最末尾.有没有办法做到这一点?

Which prints a line from the text file containing the string I specified, so I know all the code works in terms of locating the correct line. I now want to add the string ',--processed\n' to the end of the located line, as opposed to appending it to the very end of the file. Is there a way to do this?

推荐答案

您可以使用 re.sub.使用 f.read() 读取文件后,您可以使用 see f.seek(0) 倒回开头并使用 f.write() 写你的新内容(你需要用 r+ 标志打开文件):

You can use re.sub. After reading the file with f.read() you can use see f.seek(0) to rewind to the beginning and use f.write() to write your new content (you need to open the file with r+ flag):

file.txt 的内容:

Line1
Line2
Line3
Line4

脚本:

import re

SubjectName = 'Line3'

with open('file.txt', 'r+') as f:
    s = f.read()
    new_s = re.sub(r'^(.*{}.*)$'.format(re.escape(SubjectName)), lambda g: g.group(0) + ',--processed', s, flags=re.MULTILINE)
    f.seek(0)
    f.write(new_s)

运行 file.txt 后包含:

Line1
Line2
Line3,--processed
Line4

这篇关于如何使用python将字符串附加到文件中间的一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 20:45