Getting Indentation error while executing try block

1.2k views Asked by At

I am getting an Indentation error,while executing below code.

import pyodbc
import shutil
import pandas as pd
import numpy as np

def My_function():
data = pd.read_excel(r'my excel path')

    dataincsv = data.to_csv(r'export into my csv path',sep=r'|')

    cnxn = pyodbc.connect('''connection string''')
    stmt1 =  """Select column 1 from mytable"""
        try:
            Out_service = pd.read_sql(stmt1,cnxn)
        except:
            print("File format might be wrong,check the error")
        else:
            print(Out_service)
            exit()

Getting below error when i run the code

line 14 try: ^ IndentationError: unexpected indent

3

There are 3 answers

1
Jonatas CD On

If the code you've pasted here is the exactly one you're using, there's no reason to indent the try.

It should be like:

dataincsv = data.to_csv(r'export into my csv path',sep=r'|')

cnxn = pyodbc.connect('''connection string''')
stmt1 =  """Select column 1 from mytable"""
try:
    Out_service = pd.read_sql(stmt1,cnxn)
except:
    print("File format might be wrong,check the error")
else:
    print(Out_service)
    exit()

The try block should at the same level as the previous line.

EDIT: I see that you updated your code, so my answer is a bit incomplete, but you still have problems in your indentation.

0
pyeR_biz On
def My_function():
    data = pd.read_excel(r'my excel path')
    dataincsv = data.to_csv(r'export into my csv path',sep=r'|')

    cnxn = pyodbc.connect('''connection string''')
    stmt1 =  """Select column 1 from mytable"""
    try:
        Out_service = pd.read_sql(stmt1,cnxn)
    except:
        print("File format might be wrong,check the error")
    else:
        print(Out_service)
        exit()
0
wowwee On

Here is how the function should look as far as indentation, also in some text editors if you indent with Tab and spaces it can cause an issue. If the issue still persists it's most likely due to that. Hope this helps, happy coding!

def My_function():
    data = pd.read_excel(r'my excel path')
    dataincsv = data.to_csv(r'export into my csv path',sep=r'|')

    cnxn = pyodbc.connect('''connection string''')
    stmt1 =  """Select column 1 from mytable"""
    try:
        Out_service = pd.read_sql(stmt1,cnxn)
    except:
        print("File format might be wrong,check the error")
    else:
        print(Out_service)
        exit()