def truncate_text_file(input_file, output_file, max_lines):
"""Truncates a text file to a maximum number of lines."""
try:
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
lines = infile.readlines() # Read all lines
for i in range(min(max_lines, len(lines))): # Iterate up to max_lines or file length
outfile.write(lines[i]) # Write lines to the output file
print(f"File '{input_file}' truncated to {max_lines} lines and saved to '{output_file}'.")
except FileNotFoundError:
print(f"Error: Input file '{input_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Example usage:
truncate_text_file("input.txt", "output.txt", 10) # Truncate input.txt to 10 lines and save to output.txt
Add your comment