如何在Python中解决这个值错误? [英] How can I solve this valueerror in Python?

查看:219
本文介绍了如何在Python中解决这个值错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试读取文本文件(number.txt)中的行并写入列表。



我的代码块:



read = open('number.txt')



#使用readline()读取第一行



line = read.readline()

#使用读取行进一步阅读。

#如果文件是不是空的一直读一行,直到文件是空的



aList = []



而行:



aList.append(int(line.strip()))#Line 17就在这里

line = read.readline ()



read.close()

print(aList)

但我收到此错误。



Traceback(最近一次调用最后一次):

文件WriteInList.py,第17行,< module>

aList.append(int(line.strip()))

ValueError:基数为10的int()的无效文字:''



我尝试过:



我使用了strip()

我搜索了一下,但我无法弄明白。

I'm try to read lines in a text file (number.txt) and write into a List.

My code block:

read = open('number.txt')

# use readline() to read the first line

line = read.readline()
# use the read line to read further.
# If the file is not empty keep reading one lineat a time, till the file is empty

aList = []

while line:

aList.append(int(line.strip())) #Line 17 is Here
line = read.readline()

read.close()
print(aList)
But I'm getting this error.

Traceback (most recent call last):
File "WriteInList.py", line 17, in <module>
aList.append(int(line.strip()))
ValueError: invalid literal for int() with base 10: ''

What I have tried:

I used strip()
I searched about that, however I could not figure out.

推荐答案

它告诉您该行包含无法转换为 int 的文本。 strip()只会删除前导和尾随空格。



要处理此类情况,您可以使用尝试 - ,但

It tells you that the line contains text that can't be converted to an int. strip() will only remove leading and trailing white spaces.

To handle such cases you can use try - except:
for line in read:
    try:
        num = int(line.strip())
        aList.append(num)
    except:
        print "Not a number in line " + line

请注意,我在循环时更改了 for 循环文件对象,因为这样更有效。

Note that I have changed the while loop to a for loop on the file object because that is more efficient.


这篇关于如何在Python中解决这个值错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆