parsing file in python -
i'm trying parse 2 pipe/comma separated files , if particular field matches in file create new entry in 3rd file.
code follows:
#! /usr/bin/python fo = open("c-1.txt" , "r" ) line in fo: #print line fields = line.split('|') src = fields[0] f1 = open("airport.txt", 'r') f2 = open("b.txt", "a") #with open('c.csv', 'r') f1: # line1 = f1.read() line1 in f1: reader = line1.split(',') hi = false target = reader[0] if target == src , fields[1] == 'zht': print target hi = true f2.write(fields[0]) f2.write("|") f2.write(fields[1]) f2.write("|") f2.write(fields[2]) f2.write("|") f2.write(fields[3]) f2.write("|") f2.write(fields[4]) f2.write("|") f2.write(fields[5]) f2.write("|") f2.write(reader[2]) if hi == false: f2.write(line) f2.close() f1.close() fo.close()
the matching field gets printed 2 times in new file. reason?
the problem seems reset hi
false
in each iteration of loop. lets second line matches, third not. set hi
true
in second line, false
again in third, , print original line
.
try this:
hi = false line1 in f1: reader = line1.split(',') target = reader[0] if target == src , fields[1] == 'zht': hi = true f2.write(stuff) if hi == false: f2.write(line)
or, assuming 1 line ever match, use for/else
:
for line1 in f1: reader = line1.split(',') target = reader[0] if target == src , fields[1] == 'zht': f2.write(stuff) break else: f2.write(line)
also note replace series of f2.write
statements one, joining several parts |
:
f2.write('|'.join(fields[0:6] + [reader[2]])
Comments
Post a Comment