Hi all,

A question for you. I have these types of files at my work (.sj extension) that I need to work with and I'm wondering if there is a way to read from the file like a text file (the .sj files can be opened / read by notepad). The .sj files basically have a bunch of code in them which I'm extracting the comments from.

My program can currently open a .txt file and extract the comment blocks but when I change the file extension it doesn't read in the text. Any ideas? Thanks.

def readComments (textfile):
comments = []
inComment = False
for i, line in enumerate(open(textfile.name)):  
         if "//***" in line:            
            inComment = not inComment
        elif inComment: 
            line = line.lstrip("//")    
            comments.append((i, line)) 
        textfile.close()                
return comments

This should be textfile, not textfile.name (a simple "print line" will show that nothing was read). Also, look at the indents. I am assuming that this was a cut and paste error as the interpreter should give an error for the code you posted. Also, textfile.close() doesn't do anything. It is not the file name that you close but the pointer, which in the case is done by Python's garbage collector.

def readComments (textfile):         ## <-- textfile
    comments = []
    inComment = False
    for i, line in enumerate(open(textfile.name)): # <-- textfile.name

Edited 7 Years Ago by woooee: n/a

Thanks for the response.

Well what I'm passing into readComments() is actually the file object, so when I try to call:

for i, line in enumerate(open(textfile)):

The interpreter yells at me saying it needs a string value. And yes there are indentation errors too sorry about that.

My code does work, it is the matter of reading in the .sj files that I'm concerned with (.txt files work fine). Any ideas? Thanks for your help.

what I'm passing into readComments() is actually the file object

If that is the case then there's no reason to open it again. Simply iterate over the file object

Ok thx if fixed the code up a bit.

It is still not reading in the .sj file tho. Apparently it opens it but it does not read in any text. Any ideas for how to fix this?

Ok thx if fixed the code up a bit.

It is still not reading in the .sj file tho. Apparently it opens it but it does not read in any text. Any ideas for how to fix this?

You need to move the textfile.close() statement outside of your for loop. Right now it closes the file on the first iteration.

This article has been dead for over six months. Start a new discussion instead.