Python list not converting into a integer

时间:2016-04-15 11:03:33

标签: python

Hi I'm trying to convert my file back into a integer, the file reads numbers but is stored in a string and I'm trying to convert it into a integer the error I keep getting is:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

My code:

with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        print (int(line)) #Trying to convert into a integer


position_of_words_list = line.split(" ")  #make into list
print (position_of_words_list)  

3 个答案:

答案 0 :(得分:3)

You are trying to convert whole string to integer.

First split that string, then cast integer on each item.

with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        if line: #checks if line is not empty    
            position_of_words_list = list(map(int, line.split())) 
            print (position_of_words_list)

#since there is only one line in txt file, you can also use something like below
with open("input.txt","r") as f:
    position_of_words_list  = list(map(int, f.read().split()))
    print position_of_words_list 

Since you have only one line, above should work. If there are more than one line, you can append each line into the list.

position_of_words_list = [] #which will be list of lists
with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        if line: #checks if line is not empty    
            position_of_words_list.append(list(map(int, line.split())))
    print (position_of_words_list)

答案 1 :(得分:1)

Since the file has only one line and the line read as string you are getting that error.

with open('t.txt','r') as d:
    for line in d:
        position_of_words_list = [int(i) for i in line.split(' ')]
    print position_of_words_list

答案 2 :(得分:0)

格式化代码时可能出错,但行变量不在for块内。

此外,如果行中有空格,则无法将其转换为int。只有当行是一个只包含数字的字符串(没有字母或任何其他特殊字符,如空格)时,它才有效。

关于错误本身,看起来迭代器正在将行转换为列表(可能是字节?)。尝试使用str(line)。