-1
from io import open
files=open("file.txt","r")
list=files.readlines()

The file I have put contains numbers and I want to sort those numbers but it does not let me because it takes it as a list of strings some idea or simple solution to solve this??

  • 1
    NIT: You don't need `io` for `open`. Also, use a `with` statement (e.g. `with open("file.txt") as f:`. This automatically closes the file for you. If you don't want to use `with`, you should close the file via `files.close()`. – Jake Tae Dec 11 '21 at 20:26
  • 1
    Related: [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines) – wwii Dec 11 '21 at 20:33
  • 1
    As a side note, "list" is not a good name for a list. See, for instance: https://stackoverflow.com/a/55115952/5785250 – fdireito Dec 11 '21 at 20:36

2 Answers2

0

just cast the read list of strings to numbers because files reads in python read as a string by default and you can always cast the string value to the needed typee

from io import open
file=open("file.txt","r")
list = []
for line in file.readlines():
  for item in line.split(' '):
    list.append(int(item))
0

One way you can proceed ahead from here onwards is that you iterate over each list of strings you got after list=files.readlines() [please use a different name for your list as it currently coincides with the keyword list], is that you create separate empty list(s) l1 (,l2, l3, etc.) and iterate over your list and covert each string number into a integer number, like:

for i in list:

       ```l1.append(int(i))```

l1 will have all of the numbers now, in integer format.