-3

我试图通过说使字符串成为整数

file = open(input("Please enter the name of the file you wish to open:" ))
while True:
    A = file.readline() 
    if(A):
        array.append(int(A[0:len(A)-1]))
    else:
        break
print("The numbers in the file are:", A)
file.close()

我创建的文件有数字:1 -3 10 6 5 0 3 -5 20

这是错误:

ValueError: invalid literal for int() with base 10: '1 -3 10 6 5 0 3 -5 2'
4

1 回答 1

4

阅读错误 -'1 -3 10 6 5 0 3 -5 2'不是一个数字。这是一个list数字。你需要先把它变成一个字符串列表。

另外,您不应该真正使用.close(). 改为使用with

fname = input("Please enter the name of the file you wish to open:" )
with open(fname) as f:
    for line in f:
        a = [int(num) for num in line.split()]
        print a
于 2012-12-18T00:20:30.300 回答