Tim
Tim

Reputation: 75

python. finding a string within a file

Background: I am trying to read from a tmx file, and trying to find a specific string within the file.

the code i have so far

import string 
mapName = "test.js"      
tmxmap = "map.tmx"           
n,y,t = 0,0,0             
with open (mapName, 'w') as f:           

with open (tmxmap, 'r') as f1:
    t_contents = f1.readlines()
    for line in t_contents: 
        if '<objectgroup' in line:
            n = t
        if '</objectgroup' in line: 
            y = t
        t = t + 1
    f1.seek(1)
    print (n,y)
    for i in range (n,y+1):
        #f.write (t_contents[i])
        for line in t_contents[i]:
            if "id" in line: 
                f.write(t_contents[i])
print ("done")
'

so you can ignore the first half of the code if you want, because that is the code i wrote to get a specific section of a file, but however within that you can see that i can search for a string within a line. the first half works fine

however when i tried to do the same at the bottom 'if 'id' in line' that part no longer works. that statement however does work when i do 'if 'i' in line.(only one char, this also works if i do 'if 'x' in line' so i am not sure what the problem is.

the part of the tmx file that i am trying to read is

<objectgroup name="Walls" visible="0">
<object id="2" x="210" y="145" width="93" height="95"/>
<object id="3" x="56" y="150" width="48" height="51"/>
<object id="5" x="184" y="117.5" width="48" height="51"/>
<object id="6" x="311" y="117.5" width="48" height="51"/>
<object id="7" x="727" y="21.5" width="48" height="51"/>
<object id="8" x="1207" y="565.5" width="48" height="51"/>
<object id="9" x="1240" y="598.5" width="48" height="51"/>
<object id="10" x="1144" y="982.5" width="48" height="51"/>
<object id="11" x="1177" y="1078.5" width="48" height="51"/>
<object id="12" x="984" y="1046.5" width="48" height="51"/>
<object id="13" x="833" y="643" width="414" height="315"/>
<object id="15" x="102" y="485" width="308" height="86"/>
<object id="16" x="421" y="485" width="438" height="86"/>
<object id="18" x="772.667" y="133.333" width="87.3333" height="436.667"/>
<object id="20" x="355" y="162" width="410" height="315"/>
<object id="21" x="759" y="662.5" width="48" height="51"/>
</objectgroup>

Upvotes: 0

Views: 51

Answers (1)

DYZ
DYZ

Reputation: 57105

Your problem lies in the extra loop. The loop for line in t_contents[i]: goes through each element of t_contents[i]. Since t_contents[i] is a string, its elements are single characters, so line is always one character and can only be equal to another single character. You need to get rid of one loop:

for i in range (n,y+1):
#    for line in t_contents[i]:
        if "id" in t_contents[i]: 
            f.write(t_contents[i])

Upvotes: 1

Related Questions