Skip to content Skip to sidebar Skip to footer

Read Txt File And Put In List With Python

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 l

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"