ikostia
ikostia

Reputation: 7597

How to determine whether specified file is placed inside of the specified folder?

Let's say I have two paths: the first one (may be file or folder path): file_path, and the second one (may only be a folder path): folder_path. And I want to determine whether an object collocated with file_path is inside of the object collocated with folder_path.

I have an idea of doing this:

import os
...
def is_inside(file_path, folder_path):
  full_file_path   = os.path.realpath(file_path)
  full_folder_path = os.path.realpath(folder_path)
  return full_folder_path.startswith(full_file_path)

but I'm afraid there are some pitfalls in this approach. Also I think there must be a prettier way to do this.

The solution must work on Linux but it would be great if you propose me some cross-platform trick.

Upvotes: 1

Views: 88

Answers (2)

Omnifarious
Omnifarious

Reputation: 56068

Use os.path.commonprefix. Here's an example based on your idea.

import os.path as _osp

def is_inside(file_path, folder_path):
    full_file_path = _osp.realpath(file_path)
    full_folder_path = _osp.realpath(folder_path)
    return _osp.commonprefix([full_file_path, full_folder_path]) == \
           full_folder_path

Upvotes: 1

Matti Lyra
Matti Lyra

Reputation: 13088

Parse the file name from the file path and do

os.path.exists(full_folder_path + '/' + file_name)

Upvotes: 0

Related Questions