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 6708 09 101112但是,当我运行代码时,出现以下错误: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例如)是完全可以的。谢谢你。
3 回答

子衿沉夜
TA贡献1828条经验 获得超3个赞
如上所述,问题是换行符。
我建议使用split()
而不是split(" ")
。这会将所有空白视为分隔符,包括换行符。因此,您将避免调用int()
on \n
。

烙印99
TA贡献1829条经验 获得超13个赞
显然,您的testing.txt最后带有换行符。添加if列表理解:
for blob in FILE:
rows.append([int(i) for i in blob.split(" ") if i.isdigit()])

元芳怎么了
TA贡献1798条经验 获得超7个赞
您可以将所有内容都放入可读的一线代码中:
with open('testing.txt') as fobj:
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。
添加回答
举报
0/150
提交
取消