1

我读了一个文件,其中包含一个数字列表(这是我以后需要的一些标识符)。

如果我的文件末尾有一个空行,我在以下代码中有一个错误:

return [ int(x)  for x in lines if not x == '' and not x == "\r\n"]

使用以下 python 输出:

  [...]
File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 453, in readChange
ListNumbers
    self.changeListNumbers = loadChangeListNumbers()
  File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 88, in loadChangeL
istNumbers
    return [ int(x)  for x in lines if not x == '' and not x == "\r\n"]
ValueError: invalid literal for int() with base 10: ''

显然我的测试if not x == '' and not x == "\r\n"不足以处理这种情况。

我做错了什么?

(如果我取消文件的最后一个空行,即如果我让文件的最后一行包含真正的数字,一切都很好)

4

1 回答 1

6

试试这个:

return [ int(line) for line in lines if line.strip() ]

这将strip来自 的所有空格和换行符line,如果它不为空(即它包含一些字符,最好是数字),它将把它转换为int.

ValueError但是,如果您的文件包含数字以外的其他字符或数字之间包含空格,它将失败(并 raise )。

于 2012-07-27T09:24:34.360 回答