【问题标题】:"TypeError: '>' not supported between instances of 'int' and 'str'" with open() function带有 open() 函数的“类型错误:'int' 和 'str' 的实例之间不支持 '>'”
【发布时间】:2020-05-14 18:49:07
【问题描述】:

好的,这是我的代码,我想从文件中读取,然后将文件中的数字附加到列表中,然后附加一些其他数字,然后打印列表中最大的数字。这是代码

f = open("snake_settings\hs.txt", "r+") #In the file, there is number "7"

scores_list = [f.read()]
scores_list.append(4)    #Random number just to test
print(max(scores_list))  #I want to print the biggest number in a list

这是错误

File "test.py", line 5, in <module>
    print(max(scores_list))
TypeError: '>' not supported between instances of 'int' and 'str'

谢谢!

【问题讨论】:

  • 你能发布一个这个测试文件的例子吗?它的格式是什么? ascii 中的数字列表,每行一个?

标签: python list file max


【解决方案1】:

f.read() 返回一个str,您无法将其与int 进行比较。你可能想要更多类似的东西:

scores_list = list(map(int, f.readlines()))

请注意,如果文件中的任何内容无法解析为 int,这将引发 ValueError

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2019-05-09
    • 1970-01-01
    • 2019-04-14
    • 2021-10-17
    • 2020-05-19
    • 2021-08-10
    相关资源
    最近更新 更多