1. def transform_file_data(input_filepath, output_filepath, transform_function):
  2. """
  3. Transforms data from an input file using a provided function and writes the transformed data to an output file.
  4. Args:
  5. input_filepath (str): The path to the input file.
  6. output_filepath (str): The path to the output file.
  7. transform_function (function): A function that takes a line from the input file as input and returns the transformed line.
  8. This function should handle string processing.
  9. """
  10. try:
  11. with open(input_filepath, 'r') as infile, open(output_filepath, 'w') as outfile:
  12. for line in infile:
  13. transformed_line = transform_function(line.strip()) # Remove leading/trailing whitespace
  14. outfile.write(transformed_line + '\n') # Add newline character
  15. except FileNotFoundError:
  16. print(f"Error: Input file not found at {input_filepath}")
  17. except Exception as e:
  18. print(f"An error occurred: {e}")
  19. if __name__ == '__main__':
  20. #Example Usage
  21. def example_transform(line):
  22. """Example transformation: convert to uppercase."""
  23. return line.upper()
  24. input_file = 'input.txt'
  25. output_file = 'output.txt'
  26. #Create a sample input file
  27. with open(input_file, 'w') as f:
  28. f.write("This is a line.\n")
  29. f.write("Another line here.\n")
  30. f.write("And a third line.\n")
  31. transform_file_data(input_file, output_file, example_transform)

Add your comment