Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if directory paths are the same

I need to evaluate whether 2 strings refer to the same directory or not (doing a simple comparison is not good enough due to possible virtual links, etc...)

I have looked into filecmp, but filecmp.cmp seems to work only for files, not directories. filecmp.dircmp does not seem to exactly fit my purpose.

Therefore, I am currently doing it this way:

if os.path.realpath(old_path) == os.path.realpath(new_path):
    raise ValueError('Need different path!')

Does anyone have a better idea? Is there any edge case in which this would not work?

like image 960
DevShark Avatar asked Mar 27 '26 00:03

DevShark


1 Answers

The function os.path.samefile can be used as it also works on directories. e.g. os.path.samefile(old_path, new_path)

See docs: https://docs.python.org/3/library/os.path.html#os.path.samefile

like image 103
ideasman42 Avatar answered Mar 29 '26 12:03

ideasman42



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!