How to write before and after some substrings in an open file in python?

I am trying to figure out how to read a file, find specific substrings and edit the entered file to write characters before and after this substring, but I'm stuck. I can only understand how to write to the end of the file, and not in the middle of the file in the middle of the line somewhere!

So, for example, let's say I have a text file:

blah blurh blap

then I have the code:

f = open('inputFile.txt', 'r+')
for line in f:                          
    if 'blah' in line:
        f.write('!')
f.close()

As it is written above, as a result, the text will say something like:

blah blurh blap!

but I need to figure out how to say this:

!blah! blurh blap

and I can't figure it out and can't find anything on the Internet about it. Any ideas?

+4
source share
5 answers

By the way, as mentioned in the comments, this is written to another, temporary file, and then renamed it.

, 2x .

import os
with open('inputFile.txt', 'r') as inp, open('outfile.txt', 'w') as out:
    for line in inp:
        out.write(line.replace('blah', '!blah!'))
# Windows doesn't let you overwrite a file, remove it old input first
os.unlink('inputFile.txt')
os.rename('outfile.txt', 'inputFile.txt')

, .

with open('inputFile.txt', 'r') as inp:
    fixed = inp.read().replace('blah', '!blah!')
with open('inputFile.txt', 'w') as out:
    out.write(fixed)
+2

, , . - :

def mod_inline(myfilepath):
  tmp = os.tmpnam()
  with open(tmp,'w') as outfile:
     with open(myfilepath, 'r') as infile:
        for line in infile:
          if 'blah' in line:
            outfile.write(line + '!')
          else:
            outfile.write(line)
  os.rename(tmp, myfilepath)
0

Open the file, use replace()to modify the contents and save the result in a line. Then you can write the line to your file.

file_name = 'inputFile.txt'

with open(file_name, 'r') as f:
    file_content = f.read().replace('blah', '!blah!')

with open(file_name, 'w') as f:
    f.write(file_content)
0
source

Login = sample.txt

blah blub blur
test hello world

Code - read the file, work with lines, go to the same file

filename = 'sample.txt'

# Read the file
with open(filename) as f:
    file_lines = f.readlines()

# Operate on the lines
char = '!'
replace = 'blah'

for i,line in enumerate(file_lines):
    file_lines[i] = line.replace(replace, '{0}{1}{0}'.format(char, replace))

# Overwrite the file with the new content
with open(filename, "w") as f:
    for line in file_lines:
        f.write(line)

Output - characters surrounding a string

!blah! blub blur
test hello world
0
source

Here's a re-module approach that allows you to be a little more flexible and define multiple substrings that should be surrounded by another string.

Code / Demo:

import re

def surround_keysubs(s, ksubs, char):
    regex = '|'.join(ksubs)
    repl_fun = lambda m: '{}{}{}'.format(char, m.group(), char)
    return re.sub(regex, repl_fun, s)

keysubs = {'blah', 'bar'}
char = '!'

with open('testfile') as f:        
    content = surround_keysubs(f.read(), keysubs, char)

with open('testfile', 'w') as out:
    out.write(content)

Demo:

$ cat testfile 
blah blurh blap
foo bar buzz
blah blurh blap
$ python surround_keysubs.py 
$ cat testfile 
!blah! blurh blap
foo !bar! buzz
!blah! blurh blap
0
source

Source: https://habr.com/ru/post/1628208/


All Articles