PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How to edit lines of a text file based on regex conditions?

 November 06, 2022     python, python-3.x, regex, regex-group, writefile     No comments   

Issue

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?


Solution

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.



Answered By - Michael M.
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing