-1

I have an issue in Python, I have this text file:

250449825306

331991628894

294132934371

334903836165

And I want to add it to a list of ints in python for example: A=[x1,x2,x3] I have written this:

f = open('your_file.txt', encoding = "utf8")

z = f.readlines()

print(z)

But it returns z=["x1,x2,x3,x4"] I am kinda stuck, is there anything I can try here? Thanks in advance!

JacksonPro
  • 3,135
  • 2
  • 6
  • 29
  • It is unclear what you want. What would the expected output be for exactly the text file you posted? – mousetail Mar 08 '21 at 11:34
  • Does this answer your question? [How to read a text file into a list or an array with Python](https://stackoverflow.com/questions/14676265/how-to-read-a-text-file-into-a-list-or-an-array-with-python) – Jyotirmay Mar 08 '21 at 11:47

2 Answers2

2

Try this:

with open("file.txt", "r") as file:
    _list = list(map(int, file.read().split("\n")))

This read the file, splits it based on the "\n" char, and makes all of ints.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
1

because of how the file is a big string youll have newlines inside the files as well in the text file ill advise not having blank newlines

to split this properly instead of readinglines instead read the entire file and split at the "\n"

f = open('file.txt', encoding="utf8")
z = f.read().split("\n")
print(z)

youll then have to change the values to be int this can be done with a map function but in case of any trailing newlines a try catch will be better

f = open('file.txt', encoding="utf8")
z = f.read().split("\n")

l = []
for x in z:
    try:
        l.append(int(x))
    except:
        pass

print(l)
epressoD
  • 136
  • 5
  • 1
    You should always close the file after you are done using it. – TheLizzard Mar 08 '21 at 11:45
  • 1
    btw it sill be simpler if you did: `with open("file.txt", "r") as file: _list = list(map(int, file.read().split("\n")))` – TheLizzard Mar 08 '21 at 11:47
  • because of the original post not closing the file I assumed that they will be closing it later in the file and yea that would also work but I wrote it that way just to be as clear as possible and also if you split the list like that you'll get values like ["5485390","","48539405"] with the extra empty string – epressoD Mar 08 '21 at 11:53