Read Txt File And Put In List With Python
Solution 1:
You just need two changes. The first is, when you're making values
, you need to take each individual character of the line, instead of the entire line at once:
values = [int(x) for x in line.strip() if x]
Now, if you run this code on its own, you'll get [[1, 0, ...], [1, 1, ...]]
. The issue is that if you call list.append
with another list as an argument, you'll just add the list as an element. You're looking for the list.extend
method instead:
intlist.extend(values)
Your final code would be:
intlist = []
withopen('arq.txt', 'r') as handle:
for line in handle:
ifnot line.strip():
continue
values = [int(x) for x in line.strip() if x]
intlist.extend(values)
print intlist
Solution 2:
If all you have is numbers and linefeeds, you can just read the file, remove the linefeeds, map the resulting string to integers, and turn that into a list
:
withopen('arq.txt') as handle:
intlist = list(map(int, handle.read().replace('\n', '')))
print intlist
Solution 3:
Here's one way you can do it. You also don't need to use handle.close()
the context manager handles closing the file for you.
intlist = []
withopen('arq.txt', 'r') as handle:
for line in handle:
ifnot line.strip():
continue
intlist[:] += [int(char) for i in line.split() forcharin i]
print(intlist)
Solution 4:
Use strip() for delete \n and filter with bool for deleting empty strings:
withopen('test.txt') as f:
lines = map(lambda x: x.strip(), filter(bool, f))
print [int(value) for number in lines for value in number]
Solution 5:
One possibility:
intlist = []
withopen('arq.txt', 'r') as handle:
for line in handle:
for ch in line.strip():
intlist.append (ch)
print intlist
Post a Comment for "Read Txt File And Put In List With Python"