Unindent与任何外部缩进级别都不匹配?

时间:2012-07-04 11:21:36

标签: python

  

可能重复:
  IndentationError: unindent does not match any outer indentation level

我有以下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 个答案:

答案 0 :(得分: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...

答案 1 :(得分:3)

使用python -tt sort.py运行您的代码。

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

答案 2 :(得分:2)

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

相关问题