(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.