1

I'm writing a script in Python. The user has to enter a folder for the scrip to run on. There is some copying and moving of files and at a certain point a folder will be deleted. So, under no circumstances do I want this script to be run on the root folder. (or current or parent for that matter)

So I need to validate this. But how do I do that since "/" “./” “.” “..” etc .. as input are all perfectly valid and existing folders using os.path.isdir().

Should I manually check the input for these system folder symbols. Or is there a better way (existing function perhaps?) to check if the input is a real existing folder, but not a system or symbolic folder like (root, current, parent, etc …)

2 Answers 2

5

You want to normalize your path by making it absolute. You probably also want to eliminate symbolic links:

import os.path

normalized = os.path.realpath(os.path.absolute(path))
if normalized == '/':
    raise ValueError("Can't use root as a destination") 

Making a path absolute eliminates any current or parent path references, as well as any doubled separators.

Sign up to request clarification or add additional context in comments.

Comments

1

Either forbid '..' in paths or use abspath to get the real path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.