带有以10为底的文件的int()的无效文字

rows = []

FILE = open("testing.txt", "r")

for blob in FILE: rows.append([int(i) for i in blob.split(" ")])

这里testing.txt包含


01 23 04   05 67

08 09 10

11

12

但是,当我运行代码时,出现以下错误:


ValueError                                Traceback (most recent call last)

<ipython-input-1-2086c8bf9ab4> in <module>()

      1 rows = []

      2 FILE = open("testing.txt", "r")

----> 3 for blob in FILE: rows.append([int(i) for i in blob.split(" ")])


ValueError: invalid literal for int() with base 10: ''

所以我的问题是:int()怎么了?我认为如果参数是整数(int(5) == 5例如)是完全可以的。谢谢你。


三国纷争
浏览 200回答 3
3回答

子衿沉夜

如上所述,问题是换行符。我建议使用split()而不是split(" ")。这会将所有空白视为分隔符,包括换行符。因此,您将避免调用int()on&nbsp;\n。

烙印99

显然,您的testing.txt最后带有换行符。添加if列表理解:for blob in FILE:&nbsp; &nbsp; rows.append([int(i) for i in blob.split(" ") if i.isdigit()])

元芳怎么了

您可以将所有内容都放入可读的一线代码中:with open('testing.txt') as fobj:&nbsp; &nbsp; rows = [[int(item) for item in row.split()] for row in fobj if row.strip()]这样做with将确保您在离开上下文后(即在确定之后)将关闭文件。顺便说一句,split()无参数的BTW专门用于拆分文件中找到的行,因为它会拆分所有空白字符:' \t\r\n\v\f'。为了避免空行的空列表,请选中row.strip()true。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python