1

I want to parse block comments in python. I order to do that I need to find comments section in .py file.

For example, my sample.py contains

'''
This is sample file for testing
This is sample file for development
'''
import os
from os import path
def somefun():
    return

I want to parse the comments section for which I am trying to do following in sampleparsing.py

tempfile = open('sample.py', 'r')
for line in tempfile: 
    if(line.find(''''') != -1):
        dosomeoperation()
        break

Since if(line.find(''''') != -1): assumes as remaining lines below as commented how to replace this string to find comments?

I tried keeping '\' (escape character) in between but I could not find out solution for this issue.

I need following two lines after parsing in sampleparsing.py:

This is sample file for testing
This is sample file for development
5
  • 1
    you do know that ''' is not block comments right? I mean it can sometimes be used that way but ... Commented Aug 5, 2013 at 17:18
  • 2
    why not import sample; print sample.__doc__? Commented Aug 5, 2013 at 17:18
  • @JoranBeasley the creator of Python, Guido Von Rossum, approves of using multi-line strings as multi-line comments. See here: twitter.com/gvanrossum/status/112670605505077248 Commented Aug 5, 2013 at 17:26
  • @houdini: Sure, a multi-line string can legitimately be used as a comment. But, it can also be used as a multi-line string. Which is what Joran said: it's not always a comment. Commented Aug 5, 2013 at 17:50
  • @rici I didnt want programmers reading this to think it was the wrong thing to do. Seemed like Joran was implying it may not be "proper" to do that. Commented Aug 5, 2013 at 17:52

2 Answers 2

2

Try "'''" as your string instead. Right now Python thinks you are still writing a string.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

tempfile = open('sample.py', 'r')
lines = tempfile.readlines()
comments = lines.split( "'''" )
tempfile.close()

Assuming the file starts with a comment block, the comment blocks should now be the odd numbered indices, 1, 3, 5...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.