Simplest way to find a single csv file using pathlib

I want to read the one and only csv file in subfolder foo, using pahtlib, without having to specify the name explicitly. This way, the code still works if the filename changes, but the precondition that there is one and only one csv file in foo is still valid.

Right now I do

from pathlib import Path

foo_dir = Path.cwd() / 'foo'
for file in foo_dir.glob('*'):
    if file.is_file() & (file.suffix = '.csv'):
        csv_file = file

which is…eh, it works, but it’s a bit wordy. Is there anything simpler I could do, without sacrificing readability?

PS how can I modify the above code so that in case there’s no csv file in foo, it throws an error?


pathlib.Path.glob is a generator that yields pathlib.Path objects, so you can invoke next on it to consume just the first path-object from the generator. You can supply an optional argument to next to prevent a StopIteration exception from being thrown when no CSV file is present (in this case, next returns None).

from pathlib import Path

if (path := next(Path("dir/to/file").glob("*.csv"), None)) is None:
    print("No .csv file present!")


from pathlib import Path

    path = next(Path("dir/to/file").glob("*.csv"))
except StopIteration:
    raise RuntimeError("No .csv file present!")