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?
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 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]
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