Home > Enterprise >  How to edit lines of a text file based on regex conditions?
How to edit lines of a text file based on regex conditions?

Time:09-23

import re

re_for_identificate_1 = r""

with open("data_path/filename_1.txt","r ") as file:
    for line in file:
        #replace with a substring adding a space in the middle
        line = re.sub(re_for_identificate_1, " milesimo", line)

        #replace in txt with the fixed line

Example filename_1.txt :

unmilesimo primero
1001°

dosmilesimos quinto
2005°

tresmilesimos
3000°

nuevemilesimos doceavo
9012°

The correct output file that I need obtiene is this:

Rewrited input filename_1.txt

un milesimo primero
1001°

dos milesimos quinto
2005°

tres milesimos
3000°

nueve milesimos doceavo
9012°

What is the regex that I need and what is the best way to replace the fixed línes in their original positions in the input file?

CodePudding user response:

You can use file.seek(0) to go beginning of the file, then write data and truncate the file. Like this:

import re

re_for_identificate_1 = "(?<!^)milesimo"

tmp = ""
with open("data.txt", "r ") as file:
    for line in file:
        line = re.sub(re_for_identificate_1, " milesimo", line)
        tmp  = line
    file.seek(0)
    file.write(tmp)
    file.truncate()

The regex you want to use is "(?<!^)milesimo" to replace every instance of "milesimo" with " milesimo" but not at the beginning of a line.

  • Related