python 杂七杂八

:vscode 创建python项目

  1. 创建一个文件夹,可以用finder也可以终端,然后用vscode打开
mkdir python_515
cd python_515
code .
  1. 配置python解释器
CMD + SHIFT + P
输入:Python: Select Interpreter
然后选择一个python解释器

  1. 创建python文件


    image.png

:python import模块

1.导入同级模块

# 如在file1.py中想导入file2.py
import file2
# 使用
file2.fuction_name()
  1. 导入下级模块dir3目录下的file3.py文件
import dir3.file3 
# 使用
dir3.file3.fuction_name()
# 方便起见可以用as起别名
import dir3.file3 as df3
# 使用
df3.fuction_name()
  1. 导入上级模块
import sys 
sys.path.append("..") 
import file1 
  1. 导入隔壁文件夹下的模块(先到上级再下级)
import sys
sys.path.append("..")
import dir3.file3 as df3

:python 文件操作

import os
os.listdir(path) # 路径下所有的文件和文件夹名称数组
os.path.join('.','.vscode') # 路径拼接返回一个字符串 './.vscode'
os.path.splitext('main.py') # ('main', '.py') 返回一个元组,文件名和后缀


:动态导入模块和调用函数

# python_518/.vscode/files/A1.py 文件
def hello():
 print('hello')

# python 执行路径: python_518
python_518 jing$ python ./.vscode/Runner.py


# 动态导入模块和调用函数路径:python_518/.vscode/Runner.py
import importlib
moduleSrc = 'files.A1'
lib = importlib.import_module(moduleSrc)
hello_fun = getattr(lib,'hello')
hello_fun()

你可能感兴趣的:(python 杂七杂八)