1. import argparse
  2. import os
  3. def sort_text_file(input_file, output_file=None, key=None, reverse=False):
  4. """Sorts a text file and writes the sorted output to a new file or overwrites the original."""
  5. try:
  6. with open(input_file, 'r') as infile:
  7. lines = infile.readlines()
  8. if key:
  9. lines.sort(key=key)
  10. else:
  11. lines.sort(reverse=reverse)
  12. if output_file is None:
  13. output_file = input_file # Overwrite original file if no output file specified
  14. with open(output_file, 'w') as outfile:
  15. outfile.writelines(lines)
  16. print(f"Successfully sorted '{input_file}' and saved to '{output_file}'")
  17. except FileNotFoundError:
  18. print(f"Error: File '{input_file}' not found.")
  19. except Exception as e:
  20. print(f"An unexpected error occurred: {e}")
  21. def main():
  22. """Parses command-line arguments and calls the sorting function."""
  23. parser = argparse.ArgumentParser(description="Sorts lines in a text file.")
  24. parser.add_argument("input_file", help="Path to the input text file.")
  25. parser.add_argument("-o", "--output_file", help="Path to the output file (optional, overwrites input if not provided).")
  26. parser.add_argument("-k", "--key", help="Function to use as the sorting key (optional).")
  27. parser.add_argument("-r", "--reverse", action="store_true", help="Sort in reverse order (optional).")
  28. args = parser.parse_args()
  29. sort_text_file(args.input_file, args.output_file, args.key, args.reverse)
  30. if __name__ == "__main__":
  31. main()

Add your comment