In this python file program, we will replace space by an underscore in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.
#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.
Steps to solve the program
- Open the first file using open(“readcontent.txt”,”r”).
- Read the data in the file using read().
- Replace the space in the data with “_” using replace() and store the output in the new variable.
- Open the second file using open(“writecontent.txt”,”w”).
- Write the new data in the second file using write().
# Open file in read mode
f1=open("readcontent.txt","r")
# Read data
data=f1.read()
# Replace space by underscore
data=data.replace(" ","_")
# Open file in write mode
f2=open("file2.txt","w")
# Write new data to file
f2.write(data)
Output: Open the writecontent.txt file to see the ouput.
My_name_is_john.
I’m_20_years_old.
I’m_learning_python_at_sqatools.
I’m_from_Australia.
display words from a file that has less than 5 characters.