Python Practice › File Handling Programs › Program 38
Replace spaces with underscores
Write a Python program to replace every space in a file with an underscore.
Output
learn_python_at_sqatools file_handling_demo
Approach
- Read, replace, write back.
Solution
with open("story.txt", "w") as f: f.write("learn python at sqatools\nfile handling demo\n") with open("story.txt") as f: text = f.read()with open("story.txt", "w") as f: f.write(text.replace(" ", "_"))print(open("story.txt").read())Output
learn_python_at_sqatools file_handling_demo
Line by line
Lines 4-7
The file is read completely before it is reopened in “w” mode, because “w” empties it immediately.
Learn the concept
New to this topic? Read the lesson, then come back.