2

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

Xantium
  • 11,201
  • 10
  • 62
  • 89
Robyn Pan
  • 63
  • 7

4 Answers4

1

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)
Xantium
  • 11,201
  • 10
  • 62
  • 89
  • 1
    @RobynPan No problem. Pleased I was helpful :) – Xantium Jun 18 '18 at 11:33
  • Hi Simon. I got another question, If I want to add a list to a certain line in C file, for example, I want to change "int a[]={}" to "int a[] ={my list}" in c file, other lines stay the same in C file. Is there a good way to do that? – Robyn Pan Jun 18 '18 at 22:30
  • You could use https://stackoverflow.com/questions/23782114/write-and-replace-particular-line-in-file search through the file and replace the entire line @RobynPan – Xantium Jun 18 '18 at 22:49
0

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)
figbeam
  • 7,001
  • 2
  • 12
  • 18
0
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

Evgeny
  • 4,173
  • 2
  • 19
  • 39
0
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:]))
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45