Context
When creating your workflows, you'll be often manipulating file path. Instead of manipulating path as string, the best way is to take advantage of Python libaries such OS.path.
Here are some examples extracted from the official Python documentation (https://docs.python.org/2/library/os.path.html)
To concatenate paths: OS.path.join
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep
) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
On Windows, the drive letter is not reset when an absolute path component (e.g.,r'\foo'
) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive,os.path.join("c:", "foo")
represents a path relative to the current directory on driveC:
(c:foo
), notc:\foo
.
os.path.join("/mnt/sharing", "agent", file_name)
To check is a directory exists: Os.path.exists
ReturnTrue
if path refers to an existing path. ReturnsFalse
for broken symbolic links. On some platforms, this function may returnFalse
if permission is not granted to executeos.stat()
on the requested file, even if the path physically exists.
os.path.exist("/tmp/d/a.dat")
To split a file path and return the head and tail: Os.path.split
Split the pathname path into a pair,(head, tail)
where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In all cases,join(head, tail)
returns a path to the same location as path (but the strings may differ). Also see the functionsdirname()
andbasename()
head, tail = os.path.split("/tmp/d/a.dat")
>>> print(tail)
a.dat
>>> print(head)
/tmp/d
To extract a file name and its extension: Os.path.splitext
Split the pathname path into a pair(root, ext)
such thatroot + ext == path
, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored;splitext('.cshrc')
returns('.cshrc', '')
.
file_base, file_ext = os.path.splitext(file_name)
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article