I made this little script to help a friend. He studies computer engineering and is doing a project where he has to make assembly files with comments and some formatting for presentation, but, as he is making a compiler. He explained to me that he needs all their assembly codes without spaces, blank lines or comments and that the other people from his group couldn't find a small and fast solution yet to convert that.
I came up with a simple solution to it using Python:
- The script gets the filename or path
- Opens it and creates an output file (can be changed to another input for the user to type the output file name)
- Then it iterates all the lines from the file and for each line it does the following:
- Split the line when it has a comment that is identified by
- Then it gets the first element of the split line which is everything that comes before any comment
- Now it replaces every space
"". This will get rid of all blank spaces.
- If the line had a script the end of the line will be at the second element of the list, this means that the first part will not have a "\n" at the end, do we test if the list has more than one element and if it has we add a
"\n"at the end.
- I then used
rstrip()function to check if the line is not empty, and, if it isn't we write it on the output file.
#!/usr/bin/env python # -*- coding: utf-8 -*- # Made by Iago Sousa. # email@example.com # https://github.com/iagsousa/python/blob/master/scripts/removerComentariosAssembly.py f = raw_input("Insert file name or path: ") finput = open(f, "r") foutput = open("saida.txt", "w") for line in finput: l = line.split("//") l = l.replace(" ", "") if len(l) > 1: l += "\n" if l.rstrip(): foutput.write(l)
Are there any steps that I could've taken to improve my code? Is is optimal for what's intended? Those are my only questions.