Silent Bat
Silent Bat

Reputation: 21

How to make a list of numbers from a txt file in python?

I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Upvotes: 1

Views: 7273

Answers (8)

sahinakkaya
sahinakkaya

Reputation: 6056

You can convert them to integers using int:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))
txtfile.close()
print(L)

[52, 2, 103, 592, 2090, 34452, 0, 1]

Upvotes: 1

Aditya Patnaik
Aditya Patnaik

Reputation: 1776

  • but the ' around the numbers bother me : Use int(string, base)

    Returns an integer value, which is equivalent of binary string in the given base.Check here! for more

  • but arranged as one column (under each other)
  • which returns L=['52','2','103','592','2090','34452','0','1']

Assumptions:

  • numbers arranged under each other without commas that returns ['52','2','103','592','2090','34452','0','1'] as per the question

file.txt:

52
2
103
592
2090
34452
0
1

Answer:

  • imagine file.txt has 1000 numbers.

Approach 1: Use List as mentioned in the question

print([int(i.rstrip()) for i in open('file.txt')])

Size in memory

  • putting all numbers into a list would take 9032 bytes

Suggestion

Approach 2: Use Generator

print(*(int(i.rstrip()) for i in open('file.txt')))

Size in memory

  • putting all 1000 numbers into a generator would take just 80 bytes.

  • iterable like a list, but way more memory efficient, enclosed in plain parantheses ()

Cons

  • Access by index not possible with generators
print(g[4])   # TypeError: 'generator' object has no attribute '__getitem__'

Conclusion

  • if you want to just keep the numbers in the memory and want to iterate over it whenever necessary, the recommended way is to go with generators as its memory efficient
  • if want to access generators by index you can always convert a generator into a list like this list(generator)

Hope this helps!

Upvotes: 0

Eleveres
Eleveres

Reputation: 47

You should try using list comprehension and "with" keyword to make sure you don't forget to close the file.

with open('test.txt') as f:
    l = [int(line) for line in f]
print(l)

Upvotes: 3

Eeshaan
Eeshaan

Reputation: 1635

You can use int() to convert string to integer, but I'd also like to emphasize using with keyword for handling files.

L = []
with open('file.txt') as txtfile:
    for line in txtfile:
        L.append(int(line.rstrip()))

Edit: You can also read without for loop, by using map and split like so:

with open('file.txt') as txtfile:
    L = list(map(int, txtfile.read().split('\n')))

Upvotes: 1

bro
bro

Reputation: 165

try this

txtfile=open('file.txt')
L=[]
for line in txtfile:
    L.append(line.rstrip())

a = L[0].split(',')
print sorted(a, key = int)

much better if you closed that file while opening using with

with open('file.txt') as txtfile:

     b = [x for x in txtfile]
     c = b[0].split(',')
     print sorted(list(map(int, c)))

Upvotes: 0

Martin Castellon
Martin Castellon

Reputation: 111

If you want to covert them to Integers, you can use the int(string) function in Python.

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))

print(L)

According to the official Python documentation, a shorter and "more elegant" solution if you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

yourList = open("filename.txt").readlines()

Just as a recomendation:

Also you might want to consider storing data on an a JSON file. The good thing about it, is that you can use it to communicate between applications that are written in another language.

From the docs:

Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

Upvotes: 0

Dejene T.
Dejene T.

Reputation: 989

try the following:

with open('s.txt') as num:
    numbers = num.read()
    n= numbers.split()
    lst = []
    for x in range(len(n)):
        nu = n[x]
        lst.append(int(nu))
    print(lst)

output:

[1, 2, 3, 3, 4, 5, 6]

Upvotes: 0

Gabe Romualdo
Gabe Romualdo

Reputation: 245

Similar to Asocia's answer, but I would define the length of the list first (this may slightly increase speed, and is arguably a better practice):

txtfile=open('file.txt')

L = [0] * len(list(txtfile))

for lineIdx, line in enumerate(txtfile):
    L[lineIdx] = line.rstrip()

print(L)

I hope this helps.

Upvotes: 0

Related Questions