Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to decompose a path name with Python

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report