change a specific text content in all files in a folder in python

To change specific text content in all files within a folder using Python, you can use the following steps:

  1. Import the os module to access the files in the folder.
  2. Use the os.listdir() method to get a list of all files in the folder.
  3. Loop through each file in the folder.
  4. For each file, open it using the open() function.
  5. Read its contents using the read() method.
  6. Use regex to replace the targeted text with the desired content using the re.sub() method.
  7. Rewrite the file with the new content using the write() method.
  8. Close the file.

Here is the code example:

main.py
import os
import re

folder_path = "path/to/folder"
target_text = "old text"
updated_text = "new text"

for file_name in os.listdir(folder_path):
    if file_name.endswith(".txt"):  # change filter if needed
        file_path = os.path.join(folder_path, file_name)
        with open(file_path, "r") as file:
            content = file.read()
        updated_content = re.sub(target_text, updated_text, content)
        with open(file_path, "w") as file:
            file.write(updated_content)
494 chars
16 lines

In this example, the code changes all occurrences of "old text" in every .txt file in the folder with "new text". You can customize the code to suit your specific needs by changing the folder_path, target_text, and updated_text values as needed.

gistlibby LogSnag