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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
