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'
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)/bin/catIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With