configparser是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为system。下面为key=value 的配置内容
web.conf内容
'
1.py 内容 #导入模块 import os,configparser #读取文件 def load_config(cfg): print(cfg) config = configparser.ConfigParser() config.read(cfg, encoding='utf-8') return config #找到当前文件的绝对路径位置 current_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'web.conf') #获得对应数据 system 里的 user_name s = load_config(current_path).get('system','user_name') print(s)
常用的os 模块方法
import os #获得此文件的上级目录路径 current_path = os.path.dirname(__file__) #获得此文件绝对路径路径 current_path1 = os.path.abspath(__file__) #获得此文件名称 current_path2 = os.path.basename(__file__) #获得此文件的绝对路径路径的上级目录路径 current_path3 = os.path.dirname(os.path.abspath(__file__)) #把目录和文件名合成一个路径 ROOT_PATH = os.path.join(current_path3,current_path2) #判断径是否为文件 ROOT_PATH1 = os.path.isfile(current_path3) #判断括号里的文件是否存在,括号内的可以是文件路径 os.path.exists(current_path3) #递归创建目录,可以是相对或者绝对路径 os.makedirs(ROOT_PATH) 文件、目录遍历器 os.walk(current_path )