Robyn Pan
Robyn Pan

Reputation: 63

How to read numbers only to list as integer, from a file using python

I have a txt file like this:

input 0 1 2 3 4 5 6 7 0
output 127 191 223 239 247 251 253 254 0

I want to read integers 0 1 2 3 4 5 6 7 0 to a list. Here is my code:

f=open('data.txt','r')
for line in f:
        if 'input' in line:
                linestr=line.strip('input')
                #linestr=list(map(int,linestr)
                print(linestr)

The output is

0 1 2 3 4 5 6 7 0

But when i add "print(linestr[0]+1)", it shows error "TypeError: must be str, not int" Is that means the list I got is still not integer? How can I use the number as int in this list? Thx all

Upvotes: 2

Views: 929

Answers (4)

AGN Gazer
AGN Gazer

Reputation: 8378

output = []
with open('data.txt','r') as f:
    for line in f:
        l = line.split()
        if l[0] == 'input':
            output.extend(map(int, l[1:]))

Upvotes: 0

Evgeny
Evgeny

Reputation: 4541

from pathlib import Path
doc="""input 0 1 2 3 4 5 6 7 0
output 127 191 223 239 247 251 253 254 0"""
Path('temp.txt').write_text(doc)

with open('temp.txt','r') as f:
    for line in f:
        if 'input' in line:
             linestr=line.strip('input')

# here is what you have accomplished:
assert linestr == ' 0 1 2 3 4 5 6 7 0\n'
assert linestr == ' '
#you are tying to do ' '+1

linelist = map(int, linestr.strip().split(' '))
assert linestr[0]+1 == 1

P.S. your original import is a terrible workaround, please learn to use https://docs.python.org/3/library/csv.html

Upvotes: 0

figbeam
figbeam

Reputation: 7176

You can not att a str and an int inside a print()

print(linestr[0]+1)
                 ^
                 |
             not a str

You can:

print(int(linestr[0])+1)

Upvotes: 0

Xantium
Xantium

Reputation: 11605

It is still a string. Test this by type(linestr). You cannot add an integer to a string.

What you need to do is extract each value from liststr. This can be done easily using strip() and running through this list to get each value, next you need to pass it to int() to turn each value into an integer, append it to your list with integers, then you can use it as expected:

new_liststr = []
for i in liststr.split():
    new_liststr.append(int(i))

print(new_linestr[0]+1)

Or as a single liner:

new_liststr = [int(i) for i in liststr.split()] 
print(new_linestr[0]+1)

Upvotes: 1

Related Questions