Bartosz Radaczyński Bartosz Radaczyński - 1 year ago 143
Python Question

How to skip the docstring using regex

I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:

lines = open('').readlines()

How to find the line number, where the docstring ends?

Answer Source

If you're using the standard docstring format, you can do something like this:

count = 0
for line in lines:
    if line.startswith ('"""'):
        count += 1
        if count < 3:
            # Before or during end of the docstring
    # Line is after docstring

Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download