Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is valid absolute path address format

Tags:

python

I have a string which contains user input for a directory address on a linux system. I need to check if it is properly formatted and could be an address in Python 2.6. It's important to note that this is not on the current system so I can't check if it is there using os.path nor can I try to create the directories as the function will be run many times.

These strings will always be absolute paths, so my first thought was to look for a leading slash. From there I wondered about checking if the rest of the string only contains valid characters and does not contain any double slashes. This seems a little clunky, any other ideas?

like image 315
Captastic Avatar asked Nov 05 '12 16:11

Captastic


People also ask

How do you tell if a path is an absolute path?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

Is absolute a valid file path?

Alternatively referred to as file path and full path, the absolute path contains the root directory and all other subdirectories where a file or folder is contained. For example, https://www.computerhope.com/jargon/a/absopath.htm is the absolute path to this web page.

How do I check if a path is absolute in Python?

isabs() method in Python is used to check whether the specified path is an absolute path or not. On Unix platforms, an absolute path begins with a forward slash ('/') and on Windows it begins with a backward slash ('\') after removing any potential drive letter.


1 Answers

Sure the question has been edited since writing this but:

There is the os.path.isabs(PATH) which will tell you if the path is absolute or not.

Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter.

like image 114
Matt Seymour Avatar answered Oct 18 '22 02:10

Matt Seymour