Untitled

mail@pastecode.io avatar
unknown
python
a month ago
1.3 kB
1
Indexable
Never
import os
import glob
import re

def replace_specific_integer_in_file(file_path, target_integer, replacement_text):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
        
        pattern = rf'\b{target_integer}(?=\s|$)'
        new_content = re.sub(pattern, replacement_text, content)

        with open(file_path, 'w') as file:
            file.write(new_content)
        
        print(f"The integer '{target_integer}' has been replaced with '{replacement_text}' in the file '{file_path}'.")
    except FileNotFoundError:
        print(f"The file '{file_path}' does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

def replace_in_all_files_in_folder(folder_path, target_integer, replacement_text):
    print(folder_path)
    files = glob.glob(os.path.join(folder_path, '*'))
    print(files)
    for file_path in files:
        print(file_path)
        if os.path.isfile(file_path):
            replace_specific_integer_in_file(file_path, target_integer, replacement_text)

folder_path = 'C:/Users/STC/OneDrive/Desktop/testing folder/'
target_integer = '17'
replacement_text = '11'

replace_in_all_files_in_folder(folder_path, target_integer, replacement_text)
Leave a Comment