0

I have a file with text with only 0's and 1's. No space between them. Example:

0101110

1110111

I would like to read a character at a time and place them as a single element in a list of integers.

My code:

intlist = []

with open('arq.txt', 'r') as handle:
for line in handle:
    if not line.strip():
        continue

    values = map(int, line.split())
    intlist.append(values)

print intlist
handle.close()

My result:

[[101110], [1110111]]

Like if I transform the 0101110 in intlist = [0,1,0,1,1,1,0,1,1,1,0,1,1,1]. (without '\n')

ialsafid
  • 25
  • 6

5 Answers5

2

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 = []

with open('arq.txt', 'r') as handle:
    for line in handle:
        if not line.strip():
            continue

        values = [int(x) for x in line.strip() if x]
        intlist.extend(values)

    print intlist
Eric Zhang
  • 591
  • 6
  • 13
0

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 = []

with open('arq.txt', 'r') as handle:
    for line in handle:
        if not line.strip():
            continue
        intlist[:] += [int(char) for i in line.split() for char in i]

print(intlist)
Pythonista
  • 11,377
  • 2
  • 31
  • 50
0

Use strip() for delete \n and filter with bool for deleting empty strings:

with open('test.txt') as f:
    lines = map(lambda x: x.strip(), filter(bool, f))
    print [int(value) for number in lines for value in number]
JRazor
  • 2,707
  • 18
  • 27
0

One possibility:

intlist = []

with open('arq.txt', 'r') as handle:
    for line in handle:
        for ch in line.strip():
            intlist.append (ch)

print intlist
Zorgmorduk
  • 1,265
  • 2
  • 16
  • 32
0

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:

with open('arq.txt') as handle:
    intlist = list(map(int, handle.read().replace('\n', '')))

print intlist
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • @ialsafid - Note that `map()` already returns a `list` in Python 2, so you can omit the `list()` call if you don't plan on porting this to Python 3. – TigerhawkT3 Apr 09 '16 at 21:25