python文件导入与.路径

1.路径结构

test/dir0/file0.py
test/dir0/file1.py
test/file.py

2.文件内容

file.py

from dir0 import file0

file0.py

import os
import sys
sys.path.append("/home/test/dir0")
print(os.getcwd())#打印当前路径,即打印.路径
import dir0.file1
#import .file1#仅可在file0(该文件下)目录下执行

file1.py

#空

3.结论 在不同路径下运行时,当前路径为程序运行的路径。 在test下运行:

/home/test

在test/dir0下运行file0.py

/home/test/dir0

.代表当前运行python的路径。 用.导入不是一个通用且可靠的做法,只有保证程序在一个目录下运行时用.才比较可靠。 在test下执行python dir0/file0.py用.倒入则报错 在test/dir0执行python file0.py则无错 相对可靠的做法为添加子目录的父路径(见file0.py)。(仅适用于两级文件结构,多层文件结构同理)。

经验分享 程序员 微信小程序 职场和发展