python拆分文件路径
时间: 2023-10-03 08:07:33 浏览: 207
在Python中,可以使用`os.path`模块中的`splitext`函数来拆分文件路径。该函数可以将路径的文件名和后缀名分开。如果给出的是一个目录和文件名,则输出路径的文件名和后缀;如果给出的是一个目录名,则输出路径和空后缀。以下是一个示例代码:
```python
import os
file_path = "D:/test/data_expand/192.168.1.70_01_20210901163745710_250_150_4...jpg"
filename, extension = os.path.splitext(file_path)
print("filename:", filename)
print("extension:", extension)
file_path = "D:/test/data_expand/"
filename, extension = os.path.splitext(file_path)
print("filename:", filename)
print("extension:", extension)
```
输出结果为:
```plaintext
filename: D:/test/data_expand/192.168.1.70_01_20210901163745710_250_150_4..
extension: .jpg
filename: D:/test/data_expand/
extension:
```
以上代码中,`os.path.splitext(file_path)`函数将文件路径`file_path`拆分为文件名和后缀名,并分别赋值给`filename`和`extension`变量。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [【python初级】 os.path.splitext(path)将路径的文件名{只是名称}和后缀名分开](https://blog.csdn.net/jn10010537/article/details/121661609)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文