How do I take a directory name from a given dir?
Fredrik Lundh
fredrik at pythonware.com
Mon May 1 15:56:17 EDT 2006
"Merrigan" wrote:
> I am trying to write a script to backup all my company's server configs
> weekly. The script will run in a cronjob, on whatever I set it.
>
> The issue I am currently having isto "extract" the directory name from
> a given directory string. For example: from the string
> "/home/testuser/projects/" I need to extract the "projects" part. The
> problem is that the directory names that needs to be used will never be
> the same lenght, so as far as my (very limited) knowledge stretches,
> slicing and indicing is out of the question.
os.path.split(path) splits a path into directory name and "base name"
parts.
>>> import os
>>> os.path.split("/usr/bin/python")
('/usr/bin', 'python')
if you have a trailing slash, split will return an empty string for the base-
name part
>>> os.path.split("/home/testuser/projects/")
('/home/testuser/projects', '')
but you can work around that by doing an extra split:
>>> path = "/home/testuser/projects/"
>>> path, name = os.path.split(path)
>>> if not name:
... path, name = os.path.split(path)
...
>>> path
'/home/testuser'
>>> name
'projects'
hope this helps!
</F>
More information about the Python-list
mailing list