English

Write a function called replace file(), that takes pattern string, replacement string and two file names as argument. The function should read the first file and write the content into second file

Advertisements
Advertisements

Question

Write a function called replace file(), that takes pattern string, replacement string and two file names as argument. The function should read the first file and write the content into second file (creating it, if necessary). If the pattern string appear anywhere in first file, it should be replaced by replacement string in second file.

Code Writing
Advertisements

Solution

def replace_file(pattern, replacement, source_name, target_name):
    with open(source_name, "r") as source, open(target_name, "w") as target:
        for line in source:
            target.write(line.replace(pattern, replacement))

replace_file("old", "new", "input.txt", "output.txt")

The replace() method replaces every occurrence of the pattern in each line.

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

APPEARS IN

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

Englishहिंदीमराठी


      Forgot password?
Use app×