如何用相对路径来打开文件
时间: 2023-06-27 15:02:30 浏览: 52
相对路径是相对于当前工作目录的路径,可以使用以下方法来打开文件:
假设当前工作目录是 `C:\Users\username\Desktop`,要打开文件 `example.txt`,可以使用相对路径 `.\example.txt`,其中 `.` 表示当前目录。代码示例:
```python
with open('.\example.txt', 'r') as file:
data = file.read()
```
如果要打开上级目录中的文件,可以使用 `..` 表示上级目录。例如,要打开 `C:\Users\username\Documents\example.txt`,可以使用相对路径 `..\Documents\example.txt`。代码示例:
```python
with open('..\Documents\example.txt', 'r') as file:
data = file.read()
```
注意,在使用相对路径时,需要确保当前工作目录和文件路径的拼接结果是正确的。可以使用 `os.path.abspath()` 函数来获取当前脚本的绝对路径,然后再拼接相对路径。例如:
```python
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, 'example.txt')
with open(file_path, 'r') as file:
data = file.read()
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)