open textfile separated by whitespaces python 1

open textfile separated by whitespaces python

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)

Here is what the above code is Doing:
1. Create an empty list called numbers
2. Open the file
3. Iterate through each line in the file
4. Split each line into a list of numbers
5. Convert each number to an integer
6. Append the list of numbers to the result array
7. Print the result array

Similar Posts