2

so I have two files, one containing barcodes and the other containing what I want to search. File 1 is in the format:

BC01 123

BC02 124

BC03 125

my second file is in the format:

INV01 123axxxx

INV02 123bxxxx

INV03 124cxxxx

INV04 125dxxxx

Both files are tab delimited between the "tag" and the rest of the line.

So what Im currently trying to do is to search the second file with the barcodes found in the first and output them to separate files.

So the end result that I want are 3 separate files BC01, BC02, BC03 with the corresponding inventory numbers with the barcode cut off, for example:

file BC01 would read:

INV01

axxxx

INV02

bxxxx

What I have right now are lists of the separate tab delimited portions of both files: BCID, BCnumber, INVID, and INVnumber and I'm not quite sure how to proceed from here.

1 Answer 1

2

Create a dictionary out of file_1:

barcodes = {}
with open(file_1) as file_one:
    csv_reader = csv.reader(file_one, delimiter='\t')
    for row in csv_reader:
        barcodes[row[1]] = row[0]
file_one.close()

Use this to search in second file and build a output map:

output = defaultdict(list)
with open(file_2) as file_two:
    csv_reader = csv.reader(file_two, delimiter='\t')
    for row in csv_reader:
        key = row[1][:2]
        output[barcodes[key]].append(row[0])
        output[barcodes[key]].append(row[1][2:])
file_two.close()

The output dictionary would then be:

{
'BC01':['INV01', 'axxxx', 'INV02', 'bxxxx']
'BC02':['INV03', 'cxxxx']
'BC03':['INV04', 'dxxxx']
}

Now iterate through this dictionary, create files with the names of the keys and write out the contents of the file with the corresponding values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.