English

Write a function that takes three argument 1st input file, 2nd output file and 3rd transformation function. First argument is the file opened for reading, second argument is the file opened

Advertisements
Advertisements

Question

Write a function that takes three argument 1st input file, 2nd output file and 3rd transformation function. First argument is the file opened for reading, second argument is the file opened for writing and third argument is a function, which takes single string and performs a transformation of your choice and returns the transformed string. The function should reed each line in the input file, pass the line through transformation function and then write transformed line to output file. A transformation can be - capitalize first alphabet of every word.

Code Writing
Advertisements

Solution

def transform_file(input_file, output_file, transform):
    with open(input_file, "r") as source, open(output_file, "w") as target:
        for line in source:
            target.write(transform(line))


def capitalize_words(line):
    return line.title()

transform_file("input.txt", "output.txt", capitalize_words)

Here, capitalize_words is passed as a function argument and transforms every line before it is written.

shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 145]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 13. | Page 145
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×