Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: inplace_editing_example.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script demonstrates in-place editing of a text file in Python.
- Requirements:
- - Python 3.x
- Usage:
- 1. Run the script.
- 2. The script will create a sample text file called 'sample.txt' with initial content.
- 3. It will open 'sample.txt' in the default text editor.
- 4. Press [ENTER] to continue.
- 5. The script will perform in-place editing by replacing placeholders with new values.
- 6. It will then open the edited file again in the default text editor.
- 7. The script will provide verbose output messages at each step of the process.
- """
- import subprocess
- import sys
- import os
- def open_in_editor(filename):
- """
- Opens the specified file in the default text editor based on the platform.
- Args:
- filename (str): The name of the file to be opened.
- Returns:
- None
- """
- if sys.platform.startswith('win'): # Windows
- os.system(f'start notepad {filename}')
- elif sys.platform.startswith('darwin'): # macOS
- subprocess.call(['open', filename])
- elif os.name == 'posix': # Linux/Unix
- subprocess.call(['xdg-open', filename])
- # Create a sample text file
- print("Creating sample.txt...\n")
- with open('sample.txt', 'w') as file:
- file.write("The sample text is #text# and the\nnumber is #num#.")
- # Open sample.txt in default text editor
- print("\nOpening sample.txt in default text editor...\n")
- open_in_editor('sample.txt')
- # Wait for user to hit enter
- input("\nPress Enter to continue...\n")
- # Define replacements
- replacements = {
- '#text#': '"Hello World"',
- '#num#': '42'
- }
- # Perform in-place editing
- print("\nPerforming in-place editing...\n")
- with open('sample.txt', 'r+') as file:
- content = file.read()
- for old, new in replacements.items():
- content = content.replace(old, new)
- file.seek(0)
- file.write(content)
- file.truncate()
- # Open edited sample.txt in default text editor
- print("\nOpening edited sample.txt in default text editor...\n")
- open_in_editor('sample.txt')
- # Exiting program
- print("\nAll Processes Have Finished Successfully!\n\n\nExiting Program...\tGoodbye!\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement