Exercise 61 

Write a program in Python allowing to delete multiple spaces in a text file.

Solution 

In order to give an explicit solution, we will create two files:

  1. pythonCode.py
  2. myFile.txt

in the same directory

  1. In the text file myFile.txt, we will insert a the following text with multiple spaces:
    'Python       is        programming                      language'
  2. In the Python file pythonCode.py we will insert the following code:

# Opening file in read mode
file = open('myFile.txt' , 'r')
# retrieve of the file content
content = file.read()
# Now we can close the file
file.close()
# converting the string content to a list type
L = content.split()
# creating the text content with a simple space
s = ''
for x in L:
s = s + x + ' '
# Opening the file in write mode by overwriting on it
file = open('myFile.txt' , 'w')
# write the new content in the file
file.write(s)
file.close
# Now you can open manualy the file to see that all multiple space are deleted

Younes Derfoufi
my-courses.net

Leave a Reply