How to decompose a path name with Python
This article shows you how to use Python to decompose path names, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
The Python decomposition path name assumes that we use the variable fname to store a file name containing the full path, for example:
/ usr/home/hpl/scripting/python/intro/hw.py
Sometimes we need to split such a file path into the base name hw.py and the directory name / usr/home/hpl/scripting/python/intro. In the Python language, you can use the following code to do this:
Basename = os.path.basename (fname) dirname = os.path.dirname (fname) # or dirname, basename = os.path.split (fname)
The extension is extracted through the os.path.splitext function
Root, extension = os.path.splitext (fname)
Thus, the extension part of the fname, .py, is assigned to the variable extension, while the rest is assigned to the variable root. If you want to get an extension without a period, just use os.path.splitext (fname) [1] [1:].
Suppose a file is named f with an arbitrary extension. If you want to change its extension to ext, you can use the following code:
Newfile = os.path.splitext (f) [0] + ext
Here is a concrete example:
> f ='/ some/path/case2.data_source' > moviefile = os.path.basename (os.path.splitext (f) [0] + '.mpg') > moviefile 'case2.mpg' above is how to use Python to decompose path names. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.