+7 votes
by (13.6m points)

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')

5 Answers

+6 votes
by (13.6m points)

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
0 votes
by (13.6m points)

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
0 votes
by (13.6m points)

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)
0 votes
by (13.6m points)

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]
0 votes
by (13.6m points)

One possibility:

intlist = []

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

print intlist
...