Python Forum
replace or remove text from many text files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace or remove text from many text files
#21
For regex advice try https://www.rexegg.com

Here a simpler, easier to understand regex to do what you want:

import re
from pathlib import Path

afile = Path(r'/home/peterr/temp/OFINI field definitions1.txt')
newfile = Path(r'/home/peterr/temp/OFINI field definitions1.txt.altered')

# easier to understand regex
# get everything except the first and last "
# I don't think you need worry about multilinelines in your files
h = re.compile(r'\A"(.*)"\Z')

# leave the original file untouched
with open(afile) as infile, open(newfile, 'w') as outfile:
    lines = infile.readlines()
    for line in lines:
        # get rid of the newline
        line = line.strip()
        res = h.search(line)
        if res:
            newline = res.group(1) + '\n'
            outfile.write(newline)
Little bit of output:

Output:
; .OFINI ;field definitions ; .OFDEF Fd.Nxt , 2. ;00 offset from PC to next field ; .OFDEF Fd.Max , 1. ;01 maximum input characters ; .OFDEF Fd.Min , 1. ;02 minimum input characters
Reply
#22
Pedroski55 thanks,

Not only for the tutorial page, but for the reminder that just because a way, the first first way, that pops to mind to solve a problem with re, that way may not be the only or best way, I should think about both a solution and simultaneously the best solution.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  open a text file using list() Pedroski55 2 118 Feb-25-2026, 06:57 PM
Last Post: noisefloor
  How to Randomly Print a Quote From a Text File When User Types a Command on Main Menu BillKochman 13 7,275 Dec-16-2025, 05:29 PM
Last Post: zodazy
Question [SOLVED] Linefeed when writing "f" strings to text file? Winfried 5 859 Nov-04-2025, 11:51 AM
Last Post: buran
Question Parse Markdown / get the plain text SpongeB0B 8 4,293 Oct-07-2025, 06:14 PM
Last Post: noisefloor
  Picamera2 add text to camera preview GigiG 0 994 May-26-2025, 11:46 AM
Last Post: GigiG
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 13 36,671 May-20-2025, 12:26 PM
Last Post: hanmen9527
  Paste text with caret already positioned inside a placeholder; Wehaveall 2 1,704 May-14-2025, 01:12 AM
Last Post: armorerratic
  subprocess check_output text cut off Axel_Erfurt 5 1,829 Feb-20-2025, 02:15 PM
Last Post: DeaD_EyE
  Python - Hidden Text / Html Mail python1337 1 4,495 Feb-08-2025, 10:47 AM
Last Post: python1337
  Problems writing a large text file in python Vilius 4 2,035 Dec-21-2024, 09:20 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020