python不同文件夹下的py文件调用
时间: 2023-12-13 12:03:24 浏览: 34
可以使用相对路径或绝对路径来调用不同文件夹下的py文件。
1. 相对路径调用
相对路径是相对于当前工作目录的路径。假设有以下文件结构:
```
project
│ main.py
│
├───dir1
│ module1.py
│
└───dir2
module2.py
```
在main.py中调用dir1下的module1.py,可以使用相对路径:
```python
from dir1.module1 import some_function
```
在module2.py中调用dir1下的module1.py,也可以使用相对路径:
```python
from ..dir1.module1 import some_function
```
上面代码中的".."表示返回上一级目录。
2. 绝对路径调用
绝对路径是相对于文件系统根目录的路径。可以使用os模块中的path模块来构造绝对路径。假设有以下文件结构:
```
project
│ main.py
│
├───dir1
│ module1.py
│
└───dir2
module2.py
```
在main.py中调用dir1下的module1.py,可以使用绝对路径:
```python
import os
from dir1.module1 import some_function
module1_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'dir1', 'module1.py'))
print(module1_path)
some_function()
```
上面代码中,os.path.abspath()函数返回绝对路径,os.path.join()函数连接路径,os.path.dirname()函数返回文件目录,__file__变量表示当前文件路径。