Python IndentationError:意外缩进

mig*_*lfg 26 python indentation

这是我的代码...我得到缩进错误但我不知道为什么会发生.

- >

# 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
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 47

运行你的程序

python -t script.py
Run Code Online (Sandbox Code Playgroud)

如果您有混合标签和空格,这将警告您.

在*nix系统上,您可以通过运行查看选项卡的位置

cat -A script.py
Run Code Online (Sandbox Code Playgroud)

并且您可以使用该命令自动将制表符转换为4个空格

expand -t 4 script.py > fixed_script.py
Run Code Online (Sandbox Code Playgroud)

PS.编程时一定要使用编程编辑器(例如emacs,vim),而不是文字处理器.使用编程编辑器不会出现此问题.

PPS.对于emacs用户,M-x whitespace-mode将显示与cat -Aemacs缓冲区内相同的信息!


小智 8

在notepad ++中查找所有选项卡并替换为4个空格.它工作正常.


ils*_*tam 7

检查是否混合了制表符和空格,这是缩进错误的常见原因.