接收类型错误:期望的整数参数得到'str'

时间:2016-11-21 03:09:08

标签: python typeerror openfiledialog

我尝试获取一个文件并为每行创建一个单独的列表,该文件包含整数和字符串的组合,但我收到此错误TypeError: integer argument expected, got 'str'。为什么呢?

def main ():

    #open files allstar, playoffs, and regular season and create list by lines
        with open("C:\\Users\\wittn\\OneDrive\\Documents\\Project\\databasebasketball20_1\\player_regular_season.txt", "r") as reg_season:

            lst = list()

            for list_lines in reg_season : 

                line = reg_season.readlines(list_lines.strip())
                words = line.split (",")
            lst = [words]
        print (lst)            
main () 

1 个答案:

答案 0 :(得分:-1)

从文件中读取时,它会将其加载为字符串,使用int()将其强制转换为整数

如果你不知道什么值是整数,什么是字符串尝试使用这样的东西,替换lst=[words]

words = line.split(",")
lst = []
for word in words:
    try:
        lst.append(int(word))
    except:
        lst.append(word)

此算法尝试将每个单词转换为int,如果它不能将其保存为字符串

您的错误正在发生,因为从文件读取时,它会将所有内容作为字符串读取,您需要手动转换为int

希望这有帮助