Advertisement
Python253

cut_after_markers

Mar 21st, 2024
541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # Filename: cut_after_markers.py
  3. # Version: 1.00
  4. # Author: Jeoi Reqi
  5.  
  6. """
  7. This script cuts text after 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_after_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 after 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_after_marker(line, marker):
  21.     """
  22.    Remove text after the specified marker in a line.
  23.  
  24.    Args:
  25.        line (str): The input line.
  26.        marker (str): The marker to cut the line after.
  27.  
  28.    Returns:
  29.        str: The modified line without text after the marker.
  30.    """
  31.     return line.split(marker)[0] + '\n'
  32.  
  33. file_path = 'input_file.txt'  # Path to the input file
  34. output_lines = []  # List to store modified lines
  35.  
  36. try:
  37.     with open(file_path, 'r') as file:
  38.         for line in file:
  39.             # Remove text after the specified marker in each line
  40.             modified_line = remove_after_marker(line, " # ")
  41.             output_lines.append(modified_line)
  42.  
  43.     with open(file_path, 'w') as file:
  44.         # Write modified lines back to the input file
  45.         file.writelines(output_lines)
  46.  
  47.     print("Characters after '**' marker have been removed from 'input_file.txt'.")
  48. except Exception as e:
  49.     print("An error occurred:", e)
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement