Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if pathlib.Path is a file or directory without pathlib.Path exist on directory

Tags:

python

How to tell if pathlib.Path is a file or dir path without being physically present on disk. I do not want to check if the actual file exists on the disk. Something like this.

from pathlib import Path

home = Path.home()

def function_to_differentiate_file_and_dir(filepath):
    return 'file' is filepath is file
    return 'dir' if filepath is dir


assert function_to_differentiate_file_and_dir(home / 'test.txt') == 'file'
assert function_to_differentiate_file_and_dir(home / 'test.txt') == 'file'

What have you tried?:

def function_to_differentiate_file_and_dir(filepath):
    return 'file' if filepath.suffix else 'dir'
like image 946
Rahul Avatar asked Feb 03 '26 17:02

Rahul


1 Answers

To summarize my and others' comments: it's not possible. There is nothing in a path string that can indicate file or dir with any reliability (except trailing [back]slash, but it's stripped by pathlib.Path object):

>>> pathlib.Path('/var/')
PosixPath('/var')

You could try devising some heuristics for your particular use case, based on file extensions your code might encounter with pathlib.Path.suffix that you've mentioned, but in a general case there are pretty obvious issues with that approach:

  • /home/user/documents.txt/ might very well exist (being a directory)
  • on UNIX-like systems files with no extension are ubiquitous, take e.g. /bin/cat
like image 113
Nikolaj Š. Avatar answered Feb 05 '26 05:02

Nikolaj Š.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!