2

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?

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
Uclydde
  • 1,414
  • 3
  • 16
  • 33
  • Possible duplicate of [Split string on whitespace in Python](https://stackoverflow.com/questions/8113782/split-string-on-whitespace-in-python) – Elodin May 04 '19 at 01:33

2 Answers2

2

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]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

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

Elodin
  • 650
  • 5
  • 23
  • 1
    Your output are not actually a list of numbers but a list of strings! You are also not closing your file! Also what if the file has multiple lines like the ones OP @Uclydde mentioned ? Also I think it will be beneficial if you explain the code instead of posting links to various sources! – Devesh Kumar Singh May 04 '19 at 03:31
  • @DeveshKumarSingh Thanks for the tips. I will keep that in mind in the future. – Elodin May 04 '19 at 07:44
  • No problem! My suggestion was for you to update your answer to handle those cases if you can – Devesh Kumar Singh May 04 '19 at 09:12