Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 720
miguelfg Avatar asked Dec 26 '11 10:12

miguelfg


People also ask

Why does it say unexpected indent in Python?

An unexpected indent occurs when we add an unnecessary space or tab in a line of the code block. The message IndentationError: unexpected indent is shown when we run the code if this type of error is contained within your program.

How do you avoid unexpected indent errors in Python?

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.


2 Answers

Run your program with

python -t script.py 

This will warn you if you have mixed tabs and spaces.

On *nix systems, you can see where the tabs are by running

cat -A script.py 

and you can automatically convert tabs to 4 spaces with the command

expand -t 4 script.py > fixed_script.py 

PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won't get this problem with a programming editor.

PPS. For emacs users, M-x whitespace-mode will show the same info as cat -A from within an emacs buffer!

like image 103
unutbu Avatar answered Sep 17 '22 11:09

unutbu


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

like image 21
user2287824 Avatar answered Sep 16 '22 11:09

user2287824