简体   繁体   中英

How do I read in numbers (separated with whitespace) from a file?

I'm using Python 3, and I have a file in the following form: 27 4 390 43 68 817 83

How do I read these numbers in?

You can just do:

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

You need to go through each line of the file, extract all numbers out of the line by splitting on whitespace, and then append those numbers to a list.

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)

So the output will look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM