Get folder name of the file in Python -
in python command should use name of folder contains file i'm working with?
"c:\folder1\folder2\filename.xml"
here "folder2"
want get.
the thing i've come use os.path.split
twice:
foldername = os.path.split(os.path.split("c:\folder1\folder2\filename.xml")[0])[1]
is there better way it?
you can use dirname
:
os.path.dirname(path)
return directory name of pathname path. first element of pair returned passing path function split().
and given full path, can split last portion of path. example, using basename
:
os.path.basename(path)
return base name of pathname path. second element of pair returned passing path function split(). note result of function different unix basename program; basename '/foo/bar/' returns 'bar', basename() function returns empty string ('').
all together:
>>> import os >>> path=os.path.dirname("c:/folder1/folder2/filename.xml") >>> path 'c:/folder1/folder2' >>> os.path.basename(path) 'folder2'
Comments
Post a Comment