首页 > 解决方案 > 如何在 Python 中从文件中读取整数

问题描述

所以我有一个看起来像这样的文件

2
3
1  2  3  4  5  6

所以我需要在三个单独的变量中读取这个文件。对于前两个我使用这样的东西:

guests = int(input_file.readline())
length = int(input_file.readline())

但是对于第三行我需要一个列表,如何将其转换为整数,我试过这个:

sticks = input_file.readline()
sticks = [int(i) for i in sticks]

但这给了我一个错误:invalid literal for int() with base 10

标签: pythonpython-3.x

解决方案


您需要用于split()读取一行上的多个整数

sticks = [int(i) for i in sticks.split()]

推荐阅读