import os
def sort_content(file_contents, is_numeric=False):
"""Sorts the content of the file. If the content is numeric, it sorts numerically; else, alphabetically."""
try:
if is_numeric:
# Sort numerically by converting content to integers
file_contents.sort(key=lambda x: float(x.strip()))
else:
# Sort alphabetically
file_contents.sort()
except ValueError:
print("Error: Could not sort numerically. Ensure all lines are numeric.")
raise
return file_contents
def read_file(file_name):
"""Reads the content of a file and returns it as a list of lines."""
try:
with open(file_name, 'r') as file:
content = file.readlines()
return content
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
raise
except PermissionError:
print(f"Error: Permission denied to read the file '{file_name}'.")
raise
def merge_and_sort(files, output_file, is_numeric=False):
"""Merges the content of multiple files, sorts it, and writes the result to an output file."""
all_contents = []
# Read contents from all input files
for file in files:
try:
content = read_file(file)
all_contents.extend(content)
except (FileNotFoundError, PermissionError):
continue # Skip files that couldn't be read
# Sort the content
sorted_content = sort_content(all_contents, is_numeric)
# Write the sorted content to the output file
try:
with open(output_file, 'w') as out_file:
out_file.writelines(sorted_content)
print(f"Successfully written the sorted content to '{output_file}'.")
except PermissionError:
print(f"Error: Permission denied to write to the file '{output_file}'.")
raise
def main():
"""Main function to handle input and output files, and sorting type (numeric or alphabetical)."""
# Input: List of files to be merged and sorted
files = input("Enter the file names to merge (comma separated): ").split(',')
files = [file.strip() for file in files] # Clean up the file names
# Output: Name of the output file
output_file = input("Enter the name of the output file: ").strip()
# Determine whether the content should be sorted numerically or alphabetically
file_type = input("Should the content be sorted numerically (yes/no)? ").strip().lower()
is_numeric = file_type == 'yes'
try:
merge_and_sort(files, output_file, is_numeric)
except Exception as e:
print(f"An error occurred: {e}")
# Run the program
if __name__ == "__main__":
main()
Output
Enter the file names to merge (comma separated): file1.txt, file2.txt, file3.txt
Enter the name of the output file: merged_sorted.txt
Should the content be sorted numerically (yes/no)? yes
Successfully written the sorted content to 'merged_sorted.txt'.
Enter the file names to merge (comma separated): file1.txt, file2.txt, file3.txt
Enter the name of the output file: merged_sorted.txt
Should the content be sorted numerically (yes/no)? no
Successfully written the sorted content to 'merged_sorted.txt'.