[PYTHON] File matching

Matching script for file A and file B Extract only key-matched records from file B

# -*- coding: utf-8 -*-

#Key matching between file A and file B
#Premise
#-File A and File B keys are sorted in ascending order
#・ File is fixed length
#

#Matching file name, output file name
fileA = "a.txt"
fileB = "b.txt"
fileOut = "out.txt"

#File record size
recsizeA = 4
recsizeB = 8

#Key start position
keyposA = 0
keyposB = 0

#Key length
keysize = 2


#-----------------------------------------------
#Start processing
#-----------------------------------------------
fpa = open(fileA, 'rb')
fpb = open(fileB, 'rb')
fpout = open(fileOut, 'wb')

reca = fpa.read(recsizeA)
recb = fpb.read(recsizeB)

#Repeat until one of the files becomes unreadable
while len(reca) == recsizeA and len(recb) == recsizeB :
    if reca[keyposA:keysize] == recb[keyposB:keysize] :
        fpout.write(recb)
        recb = fpb.read(recsizeB)
    elif  reca[keyposA:keysize] < recb[keyposB:keysize] :
        reca = fpa.read(recsizeA)
    elif  reca[keyposA:keysize] > recb[keyposB:keysize] :
        recb = fpb.read(recsizeB)

fpa.close()
fpb.close()
fpout.close()
        

Recommended Posts

File matching
File creation
Read file
File operations
Script python file
syslog file rename
Duplicate file removal
Python file processing
Empty file detection
[Linux] File search
astropy: fits file
Matching karaoke keys
Nginx config file