Im trying to iterate through two different text files and create one consolidated file based on the account number found at the beginning of each line in both files. I begin by reading the main file which contains statement data and read each line until I find an account number that doesn't match the previous line, I then start iterating through the second file and try to match up any matching account numbers with the previous block from file 1. I am having trouble when I get to this part.
Some sample data would be:
File1 .... File2
000990 000990 is my partner 000990 000990 is my partner 000760 000530 is my partner 000760 000530 is my partner 000530 000999 is my partner 000530 000999 is my partner 000999Desired Output
000990 000990 000990 is my partner 000990 is my partner 000760 000760 000530 000530 000开发者_开发问答530 is my partner 000530 is my partner 000999 000999 is my partner 000999 is my partnerThis is the code I have tried so far. Any help or suggestions would be greatly appreciated. Thanks
x=open('testaccount.txt')
y=open('accountpartner.txt')
count=1
inv_count=1
for line in x:
if count==1:
a=x.readline()
print('S'+line, end='')
if line[0:6]==a[0:6]:
print('S'+line, end='')
elif line[0:6]!=a[0:6]:
for inv_line in y:
if inv_count==1:
b=y.readline()
if b[0:6]==a[0:6]:
print('I',b,end='')
inv_count+=1
print('break')
print('S'+line,end='')
a=line
count=1
continue
count+=1
print('this is a',a)
Use dictionaries for this. It's much simpler that writing your own sort-merge.
with open('accountpartner.txt') as aFile:
lookup = {}
for line in aFile:
lookup[line[:6]]= line
def make_groups( source ):
group = []
key= None
for line in source:
if line[:6] != key:
if group: yield key, group
group= []
key= line[:6]
group.append( line )
if group: yield key, group
with open('testaccount.txt') as main:
for key, group in make_groups( main ):
if key in lookup:
print key, group, lookup
else:
print key, group, None
精彩评论