import argparse
import os
def sort_text_file(input_file, output_file=None, key=None, reverse=False):
"""Sorts a text file and writes the sorted output to a new file or overwrites the original."""
try:
with open(input_file, 'r') as infile:
lines = infile.readlines()
if key:
lines.sort(key=key)
else:
lines.sort(reverse=reverse)
if output_file is None:
output_file = input_file # Overwrite original file if no output file specified
with open(output_file, 'w') as outfile:
outfile.writelines(lines)
print(f"Successfully sorted '{input_file}' and saved to '{output_file}'")
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
def main():
"""Parses command-line arguments and calls the sorting function."""
parser = argparse.ArgumentParser(description="Sorts lines in a text file.")
parser.add_argument("input_file", help="Path to the input text file.")
parser.add_argument("-o", "--output_file", help="Path to the output file (optional, overwrites input if not provided).")
parser.add_argument("-k", "--key", help="Function to use as the sorting key (optional).")
parser.add_argument("-r", "--reverse", action="store_true", help="Sort in reverse order (optional).")
args = parser.parse_args()
sort_text_file(args.input_file, args.output_file, args.key, args.reverse)
if __name__ == "__main__":
main()
Add your comment