如何从文件中读取数字(用空格分隔)?

时间:2019-05-04 01:27:29

标签: python-3.x file

我正在使用Python 3,并且具有以下格式的文件: 27 4 390 43 68 817 83

如何读取这些数字?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

file = open("file.txt","r")
firstLine = file.readline()
numbers = firstLine.split() # same as firstLine.split(" ")
# numbers = ["27", "4", "390"...]

https://www.mkyong.com/python/python-how-to-split-a-string/

https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

Split string on whitespace in Python

Split a string with unknown number of spaces as separator in Python

答案 1 :(得分:1)

您需要遍历文件的每一行,通过在空格上分割来提取所有数字,然后将这些数字附加到列表中。

numbers = []

#Open the file
with open('file.txt') as fp:
    #Iterate through each line
    for line in fp:

        numbers.extend( #Append the list of numbers to the result array
            [int(item) #Convert each number to an integer
             for item in line.split() #Split each line of whitespace
             ])

print(numbers)

所以输出看起来像

[27, 4, 390, 43, 68, 817, 83]