Replace spaces with underscores

EasyFile Handling Programs · 38 of 38

Write a Python program to replace every space in a file with an underscore.

Advertisement
Output
learn_python_at_sqatools
file_handling_demo

Approach

  1. Read, replace, write back.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment