python 输出文件路径的后缀
时间: 2023-04-11 18:00:47 浏览: 128
文件路径的后缀通常指文件的扩展名,例如 ".txt"、".jpg"、".py" 等。在 Python 中,可以使用 os.path 模块中的 splitext() 函数来获取文件路径的后缀名。例如:
import os
file_path = "/path/to/file.txt"
file_ext = os.path.splitext(file_path)[1]
print(file_ext) # 输出:.txt
相关问题
python拆分文件路径
在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 ]
python判断文件后缀名
要判断文件后缀名,可以使用Python的内置函数`os.path`和`splitext()`方法。下面是一个示例代码:
```python
import os
def get_file_extension(file_path):
_, extension = os.path.splitext(file_path)
return extension
file_path = '/path/to/file.txt'
extension = get_file_extension(file_path)
print(extension) # 输出:.txt
```
在这个例子中,`get_file_extension()`函数接受文件路径作为参数,并使用`os.path.splitext()`方法将文件路径分割成文件名和后缀名。然后,我们返回后缀名部分作为结果。
你可以将`file_path`变量替换为你想要判断后缀名的文件路径。