How to check if a path in python is a file? [closed]

I was working on a script that does something with the files in a given folder. Put some checks in place to assure that the path given (as a string) is a directory path and is absolute.

if not (os.path.isdir(dirpath) and os.path.isabs(dirpath)):
    error_message = f"Path given: "{dirpath}" :was inappropriate for required uses."
    raise Exception(error_message)

But while testing it on a folder, I got some unexpected results. The folder contained some pdfs in it and the function only extracts the “files” in a folder and ignores any subfolders.

file_list: list[str] = [os.path.join(dirpath, file) for file in os.listdir(dirpath) if os.path.isfile(file)]

But it ignored all pdfs and marked them as “not files”. So, how can I check if a path is any file and not just a regular file? I can check if it has an extension or not. But I don’t have any good method of doing that.

Checked some other ways to do it, for example:-


But that didn’t work either.

I have now settled for checking if it is not a directory path. But it could be useful to know about any other ways.

So, any way to do it?

Edit: Difference between any file and a regular file:-
Any file: Any file means that a file with any extension(s). Ex:-, test.h etc.
Regular file: I used the term “regular file” as that is how they are described in the official documentation. A possible definition could be here.

And the pathlib.Path(filepath).is_file() method “didn’t work” meant that it produced the exct same result as the os.path.isfile() method.

Also, I don’t want to check for a specific extension either. I want it to work for any file.


you could try

file_list = [os.path.join(dirpath, file) for file in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, file))]