1

I have a folder in which the files are all named like

"12345input789"

"12345output291"

I want to find each pair of files where the start bit ("12345") matches and perform some operation on both of the files

for file_name in os.listdir(directory):
    if "input" in filename:
         input = os.path.join(directory, file_name)
          # how do i extract the output name string here
    else:
        continue 

thanks in advance.

1 Answer 1

1

You could save all file names in two dictionaries:

inputs, outputs = {}, {}
for file_name in os.listdir(directory):
    if "input" in filename:
         pre, _, post = filename.partition("input")
         inputs[pre] = filename
    elif "output" in filename:
         pre, _, post = filename.partition("output")
         outputs[pre] = filename

# Now you can iterate over all inputs:
for prefix, input_filename in inputs.items():
    output_filename = outputs[prefix]
    do_stuff(input_filename, output_filename)

This will of course crash if there is no matching output file for an input file, so make sure that isn't the case, or handle it.

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

3 Comments

partition, very nice! so my solution is to sort os.list.dir and iterated over zip(sorted_file_list, range(len(sorted_file_list))). Then the output file is always index + 1, but that only due to the format of the file name... your solution is nice. I think I am going to need this partition function anyway to fetch the correct name for the output.
Instead of zip(x, range(len(x))) use enumerate(x) (you'll just have to swap the order of the names you're binding).
cool, didn't know about that either. maybe i should ask more questions on stack overflow.

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.