[python] Python IndentationError: unexpected indent

Here is my code ... I am getting indentation error but i don't know why it occurs.

->

# loop
while d <= end_date:
    # print d.strftime("%Y%m%d")
    fecha = d.strftime("%Y%m%d")
    # set url
    url = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1'
    # Descargamos fichero
    response = urllib2.urlopen(url)
    # Abrimos fichero
    output = open(fname,'wb')
    # Escribimos fichero
    output.write(response.read())
    # Cerramos y guardamos fichero
    output.close()
    # fecha++
    d += delta

This question is related to python indentation

The answer is


You can't mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don't mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn't match the following identations!


Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it


find all tabs and replaced by 4 spaces in notepad ++ .It worked.


Check if you mixed tabs and spaces, that is a frequent source of indentation errors.