Removing line numbers from a Python Code

来源:转载

While we do like to write the codes ourselves, oftentimes, one finds codes online that can be re-used. I personally try to find these codes, understand them, make any changes if required, and then use it for my own purpose.

3. import random

I am talking about something like the above. There are two options now

Remove manually: Easy way out. Does not works good when the code runs into hundreds of lines. Remove using a code: When the code runs into hundred of lines or when you might feel lazy, it’s better to use a code. Below is the code that I used for one of the cases. This should work, with slight modifications, for almost all the cases. Remove using Notepad ++ : Actually I tried using this at first, but it didn’t seem to work. After a couple of times, I thought of shifting to code. Maybe this can help someone else.

Below is the macro way. This is more intuitive for non-technical people:

1) Place cursor on the first line (any cursor position)

2) Click : Macro -> Start Recording

3) Do the following key press activities:

* Press the Home key * Press Delete key 27 times (till you reach the intended character)* Press down arrow button.

4) Click : Macro -> Stop Recording

5) Click : Run Macro Multiple times -> select Run until the end of file -> click Run.

Python code to remove line numbers

import sysimport ref = open('<program name>_Modified.py', 'wb')def remove_line_numbers(line): new_line = re.sub(r"/s*/d*/./s", "", line) return new_lineif __name__ == "__main__":file = '<program name>.py'o = open(file,"rb")for line in o: line = remove_line_numbers(line) print line f.write(line)o.close()f.close()

Hope this code helps many of you.

Happy Python-ing!

分享给朋友:
您可能感兴趣的文章:
随机阅读: