Advertisement
Python253

inplace_editing_example

Apr 30th, 2024
786
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: inplace_editing_example.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script demonstrates in-place editing of a text file in Python.
  9.  
  10. Requirements:
  11. - Python 3.x
  12.  
  13. Usage:
  14. 1. Run the script.
  15. 2. The script will create a sample text file called 'sample.txt' with initial content.
  16. 3. It will open 'sample.txt' in the default text editor.
  17. 4. Press [ENTER] to continue.
  18. 5. The script will perform in-place editing by replacing placeholders with new values.
  19. 6. It will then open the edited file again in the default text editor.
  20. 7. The script will provide verbose output messages at each step of the process.
  21.  
  22. """
  23.  
  24. import subprocess
  25. import sys
  26. import os
  27.  
  28. def open_in_editor(filename):
  29.     """
  30.    Opens the specified file in the default text editor based on the platform.
  31.  
  32.    Args:
  33.        filename (str): The name of the file to be opened.
  34.  
  35.    Returns:
  36.        None
  37.    """
  38.     if sys.platform.startswith('win'):  # Windows
  39.         os.system(f'start notepad {filename}')
  40.     elif sys.platform.startswith('darwin'):  # macOS
  41.         subprocess.call(['open', filename])
  42.     elif os.name == 'posix':  # Linux/Unix
  43.         subprocess.call(['xdg-open', filename])
  44.  
  45. # Create a sample text file
  46. print("Creating sample.txt...\n")
  47. with open('sample.txt', 'w') as file:
  48.     file.write("The sample text is #text# and the\nnumber is #num#.")
  49.  
  50. # Open sample.txt in default text editor
  51. print("\nOpening sample.txt in default text editor...\n")
  52. open_in_editor('sample.txt')
  53.  
  54. # Wait for user to hit enter
  55. input("\nPress Enter to continue...\n")
  56.  
  57. # Define replacements
  58. replacements = {
  59.     '#text#': '"Hello World"',
  60.     '#num#': '42'
  61. }
  62.  
  63. # Perform in-place editing
  64. print("\nPerforming in-place editing...\n")
  65. with open('sample.txt', 'r+') as file:
  66.     content = file.read()
  67.     for old, new in replacements.items():
  68.         content = content.replace(old, new)
  69.     file.seek(0)
  70.     file.write(content)
  71.     file.truncate()
  72.  
  73. # Open edited sample.txt in default text editor
  74. print("\nOpening edited sample.txt in default text editor...\n")
  75. open_in_editor('sample.txt')
  76.  
  77. # Exiting program
  78. print("\nAll Processes Have Finished Successfully!\n\n\nExiting Program...\tGoodbye!\n")
  79.  
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement