0

I am trying to find the first result of a file found in a root directory without using a for loop.

Is that possible? I tried using rglob and os.walk() but I still end up needing a for loop to get to my result which wastes time as I only need the first result I get.

i used this post to try and use it with rglob but unfortunately it did not work for me:

fp = r"C:\Users\AnxPi\Desktop\test_DS"

fp_pickle = Path(fp).rglob('*test.pkl')
print(fp_pickle)

Output:

<generator object Path.rglob at 0x0000023957C84CF0>

It only works if I do the following, which is the same as running a for loop:

sorted(Path(fp).rglob(*test.pkl'))[0]

anxiousPI
  • 183
  • 1
  • 12

1 Answers1

2

To get the first value of a generator, use next().

first_value = next(Path(fp).rglob('*test.pkl'))

If you don't want it to raise StopIteration if the generator is exhausted, pass in a sentinel value suitable for your use case to return instead:

first_value = next(Path(fp).rglob('*test.pkl'), None)
AKX
  • 152,115
  • 15
  • 115
  • 172