def transform_file_data(input_filepath, output_filepath, transform_function):
"""
Transforms data from an input file using a provided function and writes the transformed data to an output file.
Args:
input_filepath (str): The path to the input file.
output_filepath (str): The path to the output file.
transform_function (function): A function that takes a line from the input file as input and returns the transformed line.
This function should handle string processing.
"""
try:
with open(input_filepath, 'r') as infile, open(output_filepath, 'w') as outfile:
for line in infile:
transformed_line = transform_function(line.strip()) # Remove leading/trailing whitespace
outfile.write(transformed_line + '\n') # Add newline character
except FileNotFoundError:
print(f"Error: Input file not found at {input_filepath}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
#Example Usage
def example_transform(line):
"""Example transformation: convert to uppercase."""
return line.upper()
input_file = 'input.txt'
output_file = 'output.txt'
#Create a sample input file
with open(input_file, 'w') as f:
f.write("This is a line.\n")
f.write("Another line here.\n")
f.write("And a third line.\n")
transform_file_data(input_file, output_file, example_transform)
Add your comment