使用python,获取当前的工作路径,python模块的搜索路径,hello_world.txt文件的绝对路径,从绝对路径中拆分出最后一级文件名,从绝对路径中提取出目录名,从绝对路径中拆分出目录和文件名,将拆分出的目录和文件合成成一个路径
时间: 2023-09-04 08:07:10 浏览: 175
获取当前工作路径的代码如下:
```python
import os
current_path = os.getcwd()
print(current_path)
```
获取python模块的搜索路径的代码如下:
```python
import sys
module_paths = sys.path
print(module_paths)
```
假设hello_world.txt文件的路径为`/home/user/documents/hello_world.txt`,获取它的绝对路径的代码如下:
```python
import os
absolute_path = os.path.abspath('/home/user/documents/hello_world.txt')
print(absolute_path)
```
从绝对路径中拆分出最后一级文件名的代码如下:
```python
import os
absolute_path = '/home/user/documents/hello_world.txt'
file_name = os.path.basename(absolute_path)
print(file_name)
```
从绝对路径中提取出目录名的代码如下:
```python
import os
absolute_path = '/home/user/documents/hello_world.txt'
directory_name = os.path.dirname(absolute_path)
print(directory_name)
```
从绝对路径中拆分出目录和文件名的代码如下:
```python
import os
absolute_path = '/home/user/documents/hello_world.txt'
directory_name, file_name = os.path.split(absolute_path)
print(directory_name, file_name)
```
将拆分出的目录和文件合成成一个路径的代码如下:
```python
import os
directory_name = '/home/user/documents'
file_name = 'hello_world.txt'
absolute_path = os.path.join(directory_name, file_name)
print(absolute_path)
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)