मराठी

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

प्रश्न

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.

कोड लेखन
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 7: Data File Handling - EXERCISE [पृष्ठ १४६]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 7 Data File Handling
EXERCISE | Q 19. | पृष्ठ १४६
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×