Playbooks

Python Script to Replace Text in Multiple Files

Here is an example of a Python script that replaces a specific text in multiple files:

import os
import glob

# specify the directory containing the files
directory = '/path/to/directory'

# specify the file extension
file_extension = '*.txt'

# specify the text to be replaced and the replacement text
old_text = 'old_text'
new_text = 'new_text'

# get a list of all the files in the directory with the specified extension
files = glob.glob(os.path.join(directory, file_extension))

# loop through the files
for file_path in files:
    # open the file and read its contents
    with open(file_path, 'r') as file:
        file_contents = file.read()
    
    # replace the text
    new_contents = file_contents.replace(old_text, new_text)
    
    # open the file again in write mode
    with open(file_path, 'w') as file:
        file.write(new_contents)

This script uses the glob library to find all the files with the specified extension in the specified directory, then loops through each file and replaces the old text with the new text. You can change the directory, file extension, old text, and new text to suit your needs. Also, as an alternative, you can use os.scandir() to loop through all the files in the directory, and then use the same logic to replace the text in each file.

PyJoy

Recent Posts

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic. import psutil def monitor_network(): #…

2 years ago

Python Script for Web Scraping

Here's a basic example of web scraping in Python using the requests and BeautifulSoup libraries:…

2 years ago

Python Script to SSH and Run Commands

Here's an example of how you can use Python to SSH into a remote server…

2 years ago

Python Code Example with Classes

Here's an example of a Python class that represents a rectangle: class Rectangle: def __init__(self,…

2 years ago

Python Script Example with Main Method in Active Directory

Here is a simple Python script that interacts with Active Directory (AD) using the pyad…

2 years ago

Python Script Example for System Administrators

Here's a Python script to monitor disk usage on a system and send an email…

2 years ago