目录

在同一个文件夹下

在不同一个文件夹下

注意事项

一个方案


在同一个文件夹下

python 导入文件 python导入其他文件的函数_python

在comment.py中,导入utils.py中函数

from utils import extract_comment_content, time_fix
#使用时 
#直接用名字  如extract_comment_content

或者

import utils 
#使用
utils.extract_comment_content

在comment.py中,导入items.py函数

from items import CommentItem
#使用方法类似案例1

在不同一个文件夹下

python 导入文件 python导入其他文件的函数_导包_02

红色方框要引入箭头里面的

import sys
sys.path.append('../../config/')
from database import *
print(MYSQL_CONFIG)

注意事项

使用前先将文件夹调为Source Root

python 导入文件 python导入其他文件的函数_文件名_03

一个方案

如果你是用pycharm的新建python package,你新建的目录下就会有一个__init__.py文件
你需要在导包的前面加入这样一段代码

import os, sys
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)

然后再导入相应的包,注意要先加上文件名

python 导入文件 python导入其他文件的函数_开发语言_04

如:我i的random_walk2是存放在mat2文件夹里,所以我需要先写

from mat2.random_walk2 import RandomWalk