0

Input is a txt file containing list of numbers:

62521
93897
....
107428

My approach:

with open('filelocation/file name.txt') as f:
 read_data = f.read()
print(read_data)

After this I am able to see the data in txt so I am sure now that 'open' and 'read' is working.

Now needed result:

list = [62521, 93897,.....,107428 ]

How do I convert the into a list so that I am able to go with my calculations with the list?

Alternatively is it possible to work with each numbers (62521, 93897...) directly from the txt file?

I have to do some steps of calculations with them. Will it be easier to read each line (i.e., numbers) at one go, do the whole calculations and run it in a loop rather than converting the whole input in single list?

Are there any other better solutions?

Robert
  • 7,394
  • 40
  • 45
  • 64
Anu
  • 13
  • 4
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Sergey Shubin Apr 30 '20 at 13:41

1 Answers1

1

I hope this is what u are looking for, i dont know myself if there is a better way to do it since im a beginner more or less, but converting the content of a textfile into a list is fairly easy done by using the .split() function. My approach to your problem is as follows:

def get_data():
    with open("data.txt", "r") as file:
        data = file.read()
    return data

data = get_data()
data_list = data.split()
data_list = [int(x) for x in data_list]
print(data_list)
Athos
  • 109
  • 5