Home Ask Login Register

Developers Planet

Your answer is one click away!

Lukasz February 2016

Pattern searching in a file and replacing the found results

I'm trying to write a simple program that will open text files in given directory search for all strings that match a given pattern and replace them with the desired string while removing all other info. I have two .txt files:

User_321.txt which contains:

321_AliceKelly001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly002.jpg [size_info] [date_info] [geo_location_info] ... [other info] 
321_AliceKelly003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
321_AliceKelly125.jpg [size_info] [date_info] [geo_location_info] ... [other info]

and User_205.txt which contains:

 205_CarlCarlson001.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson002.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson_003.jpg [size_info] [date_info] [geo_location_info] ... [other info]
 205_CarlCarlson007.jpg [size_info] [date_info] [geo_location_info] ... [other info]

I want User_321.txt to contain:


and User_205.txt to contain:


So I simply want to add "_" between the name and last 3 digits. I'm able to handle the case where all the entries are uniform, that is only contain entries of the following form:

     \d\d\d_[a-zA-Z]\d\d\d.jpg [size_info] [date_info] [geo_location_info] ... [other info]

with the following code:

import os, re,

path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]

desired_text = re.compile(r'\w+.jpg')
#desired_ending = re.compile(r'$[a-zA-Z]\d\d\d.jpg')

for i in range(len(text_files)):
    working_file = path + '\\' + text_fi        


bobble bubble February 2016

You can use parentheses for grouping and capturing


and replace with \1_\2 to add an underscore in between.

  • \b matches a word boundary
  • Rest like your sample form, separated in two groups.

See demo at regex101 (Python code generator)

Francesc Torradeflot February 2016

I have slightly modificated your code, handling the two different cases, and it seems to work:

import os, re

path = 'C:\\Users\\ME\\Desktop\\TEST'
text_files = [filename for filename in os.listdir(path)]

desired_text1 = re.compile(r'^\d{3}_[a-zA-Z]+\d{3}.jpg')
desired_text2 = re.compile(r'^\d{3}_[a-zA-Z]+_\d{3}.jpg')

for i in range(len(text_files)):
    working_file = path + '\\' + text_files[i]
    fin = open(working_file, 'r')
    match = ''

    for line in fin:
        mo1 = desired_text1.search(line)
        mo2 = desired_text2.search(line)
        if mo1:
            match += mo1.group()[:-7] + '_' + mo1.group()[-7:]+'\n'
        elif mo2:
            match += mo2.group() +'\n'


    fout = open(working_file, 'w')

Casimir et Hippolyte February 2016

You can do that:

with open('source.txt') as f:
    with open('destination.txt', 'w') as g:
        for line in f:
            parts = line.split(None, 1)
            if parts[0][-8:-7] == '_':
                g.write(parts[0] + '\n')
                g.write(parts[0][:-7] + '_' + parts[0][-7:] + '\n')

Feel free to change \n to \r\n if you want a Windows newline sequence.

Post Status

Asked in February 2016
Viewed 1,328 times
Voted 5
Answered 3 times


Leave an answer

Quote of the day: live life