Programming Examples

Python program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by single space


Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by single space.

Solution

fname1=input("Enter the File Name 1 : ")
fname2=input("Enter the File Name 2 : ")
fp1 = open(fname1,"r")
fp2 = open(fname2,"w")
lines = fp1.readlines()
for line in lines :
    word = line.split()
    fp2.write( " ".join(word)  )
    fp2.write("\n")
fp1.close()
fp2.close()
Output

Enter the File Name 1 : file1.txt

Enter the File Name 2 : file2.txt

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz