Path.name python
时间: 2024-05-05 22:15:33 浏览: 11
In Python, the `path.name` attribute is used to get the name of a file or directory from a given path.
For example, if we have a file path like `C:/Users/John/Documents/myfile.txt`, we can use the `name` attribute to get the name of the file (i.e. `myfile.txt`) as follows:
```python
import os
file_path = "C:/Users/John/Documents/myfile.txt"
file_name = os.path.basename(file_path) # get the filename from the path
print(file_name) # prints: "myfile.txt"
```
Similarly, we can use the `name` attribute to get the name of a directory from a given path. For example, if we have a directory path like `C:/Users/John/Documents`, we can use the `name` attribute to get the name of the directory (i.e. `Documents`) as follows:
```python
import os
dir_path = "C:/Users/John/Documents"
dir_name = os.path.basename(dir_path) # get the directory name from the path
print(dir_name) # prints: "Documents"
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)