Advertisement
Python253

cut_before_markers

Mar 21st, 2024
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # Filename: cut_before_markers.py
  3. # Version: 1.00
  4. # Author: Jeoi Reqi
  5.  
  6. """
  7. This script cuts text before specified markers in each line of a text file.
  8.  
  9. Requirements:
  10. - Python 3.x
  11.  
  12. Usage:
  13. 1. Ensure the script 'cut_before_markers.py' is in the same directory as the input text file.
  14. 2. Open the script in a text editor and edit the value of 'file_path' variable to point to the input text file.
  15. 3. Run the script using a Python interpreter.
  16. 4. The script will cut text before specified markers in each line of the input file and save the modified text back to the same file.
  17. 5. Review the console output to confirm the successful execution of the script.
  18. """
  19.  
  20. def remove_before_marker(line, marker):
  21.     """
  22.    Remove text before the specified marker in a line.
  23.  
  24.    Args:
  25.        line (str): The input line.
  26.        marker (str): The marker to cut the line before.
  27.  
  28.    Returns:
  29.        str: The modified line without text before the marker.
  30.    """
  31.     index = line.find(marker)
  32.     if index != -1:
  33.         return line[index + len(marker):] + '\n'
  34.     return line
  35.  
  36. file_path = 'input_file.txt'  # Path to the input file
  37. output_lines = []  # List to store modified lines
  38.  
  39. try:
  40.     with open(file_path, 'r') as file:
  41.         for line in file:
  42.             # Remove text before the specified marker in each line
  43.             modified_line = remove_before_marker(line, " : ")  # Edit this to your set marker
  44.             output_lines.append(modified_line)
  45.  
  46.     with open(file_path, 'w') as file:
  47.         # Write modified lines back to the input file
  48.         file.writelines(output_lines)
  49.  
  50.     print("Characters before '**' marker have been removed from 'input_file.txt'.")
  51. except Exception as e:
  52.     print("An error occurred:", e)
  53.  
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement