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]
#5
(Aug-07-2021, 11:45 AM)Axel_Erfurt Wrote: As bowlofred already wrote, make a function and then call it for every txt file

import os

folder_path = "/path/to/folder/" # your path
            
for root, dirs, files in os.walk(folder_path, topdown = False):
   for name in files:
      if name.endswith(".txt"):
        file_name = os.path.join(root, name)
        print(file_name)
        #your_function(file_name) # call your function

I tried to do it like this:

#!/usr/bin/env python3

import os
import re

folder_path = "/home/pi/Workspace/Case_02/" # your path

for root, dirs, files in os.walk(folder_path, topdown = False):
   for name in files:
      if name.endswith(".txt"):
        file_name = os.path.join(root, name)

target = "Format"

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

with open(file_name, 'r') as file :
  filedata = file.read()

filedata = re.sub(re.escape(target), str_counter, filedata)

with open(file_name, 'w') as file:
    file.write(filedata)
I set an example with three different files (Out_01.txt, Out_02.txt, Out_03.txt) but the changes to my file were only written to Out_03.txt.

Edit: I just needed to set the right amount of spaces per indentation level.
Reply


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

Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Right way to open files with different encodings? Winfried 3 4,331 Jan-18-2025, 02:19 PM
Last Post: Winfried
  [SOLVED] Sub string not found in string ? jehoshua 4 1,416 Dec-03-2024, 09:17 PM
Last Post: jehoshua
Question [SOLVED] How to replace characters in a string? Winfried 2 1,046 Sep-04-2024, 01:41 PM
Last Post: Winfried
  Trying to generating multiple json files using python script dzgn989 4 2,261 May-10-2024, 03:09 PM
Last Post: deanhystad
  [SOLVED] Loop through directories and files one level down? Winfried 3 2,298 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
  replace text in a txt cartonics 19 5,148 Jan-30-2024, 06:58 AM
Last Post: Athi
  python convert multiple files to multiple lists MCL169 6 3,306 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Replace a text/word in docx file using Python Devan 4 21,706 Oct-17-2023, 06:03 PM
Last Post: Devan
  Need to replace a string with a file (HTML file) tester_V 1 1,931 Aug-30-2023, 03:42 AM
Last Post: Larz60+
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 2,615 Aug-01-2023, 09:36 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