2

I get a file from the desktop that has a code of python like:

line 1 :#hi
line 2 :x=0
line 3 :#print x
line 4 :print "#" 
line 5 :print ' # the x is" , x 
line 6 :print "#"# 

and I want to print in the programme :

line 1 :x=0
line 2 :print "#"
line 3 :print ' # the x is" , x
line 4 :print "#"

and I run in it my programme with fopen and I get any line apart, I want to print the lines but without the #...the # must be checked if is in "" or '' and if it is when we must print the line with the #.

I have open a file and get the lines apart and checked if the # is in the line when removing it but I can't find who to check if the # is in "" or '' and if it is then print all the line.

def remove_comments(line,sep="#"):
    for s in sep:
        i = line.find(s)#find the posision of  #
        if i >= 0 :
            line = line[:i]#the line is until the # - 1
    return line.strip()

f=open("C:\Users\evogi\OneDrive\Desktop\ergasia3 pats\kodikaspy.txt","r")
for line in f :
    print remove_comments(line)

and the result is :

line 1 :
line 2 :x=0
line 3 :
line 4 :print "
line 5 :print '
line 6 :print "
3
  • You are mixing up " and ' Commented Feb 10, 2019 at 11:43
  • 1
    You need a proper parser to do this correctly. Look at the module ast. Commented Feb 10, 2019 at 11:45
  • 1
    Possible duplicate of Script to remove Python comments/docstrings Commented Feb 10, 2019 at 12:51

1 Answer 1

3

The function string.find() returns the index of first occurence of the substring. So in your case you want to look for lines where it returns 0 (then the # is the first character, i.e. a comment).

So you could do something like

def remove_comments(line,sep="#"):
    for s in sep:
        i = line.find(s)#find the posision of  #
        if i == 0 :
            line = None
    return line.strip()

f=open("C:\Users\evogi\OneDrive\Desktop\ergasia3 pats\kodikaspy.txt","r")
for line in f :
    if remove_comments(line):
        print remove_comments(line)
Sign up to request clarification or add additional context in comments.

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.