首页 文章

Unindent与任何外部缩进级别都不匹配? [重复]

提问于
浏览
1

可能重复:IndentationError:unindent与任何外部缩进级别都不匹配

我有以下python代码 .

import sys

ins = open( sys.argv[1], "r" )
array = []
for line in ins:
    s = line.split()
    array.append( s[0] ) # <-- Error here 
print array

ins.close()

python翻译抱怨道

File "sort.py", line 7
    array.append( s[0] )
                       ^
IndentationError: unindent does not match any outer indentation level

为什么这样?以及如何纠正此错误?

3 回答

  • 4

    你正在混合标签和空格(有时候会发生:) . 使用其中一个 .

    我查看了你的来源:

    s = line.split()  # there's a tab at the start of the line
        array.append( s[0] )  # spaces at the start of the line
    

    旁白:作为一个友好的建议,请考虑使用 with 打开您的文件 . 优点是,当您完成或遇到异常时,文件将自动关闭(不需要 close() ) .

    array = []
    with open( sys.argv[1], "r" ) as ins:  # "r" really not needed, it's the default.
       for line in ins:
          s = line.split()
          # etc...
    
  • 2

    python -tt sort.py 运行你的代码 .

    它会告诉你是否混合了标签和空格 .

  • 3

    使用空格或制表符确保缩进是一致的,而不是两者的混合 .

相关问题