Python - Remove simple comments from Python code

It can be used as a simple tool, but it is also quite limited and can only remove comment lines starting with #.

#using built-in functions without introducing modules 
filename = "xxx.txt" #open the file named xxx of txt file 
file = open(filename, mode='r') #open file for reading 
savefile = "ans.txt" #save the target file for the results 
file2 = open(savefile, mode='w') #open file for reading 
text = file.readlines() #read the original file line by line 
for ans in text:
#check line by line whether the first letter is #, can be extended in loop writing 
if ans[0] != '#': 
  file2.write(ans)
file.close() #close file 

Related articles