Ranga Sarin Ranga Sarin - 2 months ago 6
Python Question

else: expected an indented block

I'm getting an indent error but I can't for the life of me figure it out.

if not os.path.exists(file):
data = get_data(datapath)
if len(data)>1:
try:
text_file = open(file, "w")
text_file.write(data)
text_file.close()
f = open(file,mode='r'); msg = f.read(); f.close()
dosomething.................
except: pass
else:### HERE IS THE IDENT ERROR ####
data = get_data(datapath)
if len(data)>1:
try:
if data == open(file).read():
dosomething............
else
dosomething.......
except: pass


I've highlighted the
else
where the error is happening with a comment.

Answer

You have two issues with your code. Firstly, the indentation error that you are experiencing is probably related to the fact that you have mixed the use of tabs and spaces in indenting your code. Go through and make sure you stick to one convention throughout. If you have an editor like sublime text, you can go to View > Indentation > Convert Tabs to Spaces and it will usually fix the problem.

Secondly, there is a syntax error on the last else in your code. You are missing a colon:

if not os.path.exists(file):
    data = get_data(datapath)
    if len(data)>1:
        try:
            text_file = open(file, "w")
            text_file.write(data)
            text_file.close()
            f = open(file,mode='r'); msg = f.read(); f.close()
            dosomething.................
        except: pass
else:
    data = get_data(datapath)
    if len(data)>1:
        try:
            if data == open(file).read():
                dosomething............
            else:     #   <-----------------------    Issue is here 
                dosomething.......
        except: pass