Reputation: 21
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
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
Reputation: 1776
int(string, base)
Returns an integer value, which is equivalent of binary string in the given base.Check here! for more
under each other
without commas that returns ['52','2','103','592','2090','34452','0','1']
as per the questionfile.txt:
52
2
103
592
2090
34452
0
1
print([int(i.rstrip()) for i in open('file.txt')])
Size in memory
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 ()
print(g[4]) # TypeError: 'generator' object has no attribute '__getitem__'
list(generator)
Hope this helps!
Upvotes: 0
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
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
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
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
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
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