DAY30 模块和库的导入
官方库导入直接import 库名或from 库名 import 函数无需关心路径自定义模块导入模块需在 Python 搜索路径内同目录 / 子目录 / 手动加路径核心规则导入 找文件 执行文件路径不对就用sys.path.append()加路径import os import sys # 自动创建目录和模块文件 # 1. 创建主目录 main_dir python_import_demo os.makedirs(main_dir, exist_okTrue) # 2. 创建子目录 sub_dir os.path.join(main_dir, sub_dir) os.makedirs(sub_dir, exist_okTrue) # 3. 写入同目录模块 module_a.py module_a_content # 同目录测试模块 def hello_a(): print(✅ 我是同目录的module_a里的函数) with open(os.path.join(main_dir, module_a.py), w, encodingutf-8) as f: f.write(module_a_content) # 4. 写入子目录模块 module_b.py module_b_content # 子目录测试模块 def hello_b(): print(✅ 我是子目录sub_dir里的module_b函数) with open(os.path.join(sub_dir, module_b.py), w, encodingutf-8) as f: f.write(module_b_content) # 5. 写入上级目录模块 module_c.py创建在主目录外 module_c_content # 上级目录测试模块 def hello_c(): print(✅ 我是上级目录的module_c函数) with open(os.path.join(os.path.dirname(main_dir), module_c.py), w, encodingutf-8) as f: f.write(module_c_content) # 切换到主目录并执行导入测试 # 切换工作目录到主目录 os.chdir(main_dir) # 1. 导入同目录模块 import module_a module_a.hello_a() # 2. 导入子目录模块 # 方式1导入子目录模块 from sub_dir import module_b module_b.hello_b() # 方式2直接导入子目录模块的函数 from sub_dir.module_b import hello_b hello_b() # 3. 导入上级目录模块 # 添加上级目录到搜索路径 parent_dir os.path.abspath(..) sys.path.append(parent_dir) import module_c module_c.hello_c() print(\n 所有导入测试完成) print(f\n 生成的文件路径说明) print(f - 主目录{os.path.abspath(.)}) print(f - 上级目录模块{os.path.join(parent_dir, module_c.py)})浙大疏锦行