How to remove whitespace and comments from a text file?

Viewed 452

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)
1 Answers

To remove blank lines and trailing whitespace as well as comments, you could use:

import re

with open("file.txt", "r") as file:
    for line in file:
        line = line.rstrip()
        if line:
            if not re.match(r'\s*#', line):
                file.write(line)

Output

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)
Related