This article mainly introduces the actual operation steps of path name decomposition in Python. We will set a lot of assumptions and introduce some relevant code, in this way, you can better understand the actual operation steps of splitting the path name in Python.
In Python, we use the variable fname to store a file name that contains the complete path. For example:
- /usr/home/hpl/scripting/python/intro/hw.py
Sometimes, we need to split the file path into the basic name hw. py and directory name/usr/home/hpl/scripting/python/intro. In Python, you can use the following code:
- Basename = OS. path. basename (fname)
- Dirname = OS. path. dirname (fname)
- # Or
- Dirname, basename = OS. path. split (fname)
The extension is extracted using the OS. path. splitext function,
- root, extension = os.path.splitext(fname)
In this way, the extension Section of fname, namely. py, is assigned to the variable extension, while the other part is assigned to the variable root. If you want an extension without a dot, you only need to use OS. path. splitext (fname) [1] [1.
Assume that a file name is f and its extension is random. To change its extension to ext, you can use the following code:
- newfile = os.path.splitext(f)[0] + ext
The following is a specific example:
- >>> f = ’/some/path/case2.data_source’
- >>> moviefile = os.path.basename(os.path.splitext(f)[0] + ’.mpg’)
- >>> moviefile
- ’case2.mpg’
The above content is a detailed introduction to the path name decomposition in Python.