Python Forum
Replace String in multiple text-files [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace String in multiple text-files [SOLVED]
#6
You did not create a function and your indentations are disastrous, try this

import os
import re
 
folder_path = "/home/pi/Workspace/Case_02/" # your path
target = "Format"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

def  do_it(file_name):
    with open(file_name, 'r') as file :
        filedata = file.read()
        print(filedata)
     
        filedata = re.sub(re.escape(target), str_counter, filedata)
    
        print(filedata)
     
        with open(file_name, 'w') as file:
            file.write(filedata)
            file.close()
        
for name in os.listdir(folder_path):
    if name.endswith(".txt"):
        file_name = os.path.join(folder_path, name)
        do_it(file_name)
Reply


Messages In This Thread
RE: Replace String in multiple text-files - by Axel_Erfurt - Aug-08-2021, 04:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  replace text in a txt cartonics 19 2,235 Jan-30-2024, 06:58 AM
Last Post: Athi
  python convert multiple files to multiple lists MCL169 6 1,551 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Replace a text/word in docx file using Python Devan 4 3,406 Oct-17-2023, 06:03 PM
Last Post: Devan
  Need to replace a string with a file (HTML file) tester_V 1 768 Aug-30-2023, 03:42 AM
Last Post: Larz60+
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,135 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  splitting file into multiple files by searching for string AlphaInc 2 899 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
Question [solved] compressing files with python. SpongeB0B 1 649 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  Replace string in a nested Dictianory. SpongeB0B 2 1,207 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 836 Mar-21-2023, 03:43 AM
Last Post: mm309d
  Merging multiple csv files with same X,Y,Z in each Auz_Pete 3 1,167 Feb-21-2023, 04:21 AM
Last Post: Auz_Pete

Forum Jump:

User Panel Messages

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