I want to read a text file that contains Python source code and remove comments and extra whitespace from it.
file.txt (source code file)
#Pythonprogramtofindthefactorialofanumberprovidedbytheuser.
num= 7
factorial=1
ifnum<0:
print("Sorry,factorialdoesnotexistfornegativenumbers")
elifn um==0:
print("Thefactorialof0is1")
else:
foriinrange(1,num+1):
factorial=factorial*i
print("Thefactorialof", num," is", factorial)
I have tried reading the file and using a list comprehension to filter the lines, but it is not working to remove comments and some whitespace is being removed that I want to keep.
with open('file.txt', 'r') as file:
lines = file.readlines()
lines = [line.replace(' ', '') for line in lines]
with open('file.txt', 'w') as file:
file.writelines(lines)