Search code examples
pythonindentation

How to handle unexpected indent error in Python


Code

#!/usr/bin/python
import sys
import psycopg2
import psycopg2.extras

def init_pg94_from_sql_file(filename, connection):        
    file = open(filename, 'r')
    sql = s = " ".join(file.readlines())
    print "Start executing: " + filename + " at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + "\n" + sql 
    cursor = connection.cursor()
    cursor.execute(sql)    

    connection.commit()
    cursor.close()

but I get

  File "9.7.2015.py", line 14
    cursor.close()
    ^
IndentationError: unexpected indent

which is strange, since I do not seem to have any indentation problem.

How can you handle such an unexpected indentation challenge?


Solution

  • The line with cursor.close() has a tab in it, and the preceding ones have only leading spaces. This breaks the indentation.

    A good solution is to replace all tabs by four spaces.