A typical example of using Python to describe the path name

Source: Internet
Author: User

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:

 
 
  1. /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:

 
 
  1. Basename = OS. path. basename (fname)
  2. Dirname = OS. path. dirname (fname)
  3. # Or
  4. Dirname, basename = OS. path. split (fname)

The extension is extracted using the OS. path. splitext function,

 
 
  1. 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:

 
 
  1. newfile = os.path.splitext(f)[0] + ext 

The following is a specific example:

 
 
  1. >>> f = ’/some/path/case2.data_source’  
  2. >>> moviefile = os.path.basename(os.path.splitext(f)[0] + ’.mpg’)  
  3. >>> moviefile  
  4. ’case2.mpg’ 

The above content is a detailed introduction to the path name decomposition in Python.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.