【python】读取cfg/ini/txt配置文件
1.config.cfg文件内容:
现需读取config.cfg里的host内容:
1 # @Time : 2021/9/4 20:21 3 # @File : readCfg.py 4 import os 5 6 from configparser import ConfigParser 7 import os 8 9 class ReadCfg(): 10 def __init__(self): 11 pass 12 13 def getPath(self): 14 #获取当前目录 15 current_dir = os.path.abspath('') 16 #获取上一级目录 17 filePath = os.path.dirname(current_dir) 18 #再获取上一级目录 19 lastFilePath = os.path.dirname(filePath) 20 #拼接配置文件的路径 21 cfgPath =os.path.join(lastFilePath,'conf','config.cfg') 22 print(cfgPath) 23 return cfgPath 24 #默认获取主机的地址 25 def readCfg(self,section='hostname',option = 'host'): 26 #拼接配置文件的路径 27 con = ConfigParser() 28 con.read(self.getPath(),'utf-8') 29 res = con.get(section,option) 30 return res 31 32 if __name__ == '__main__': 33 readCfg = ReadCfg()
2.readIni.ini
1 [hostname] 2 host = http://127.0.0.1:8088 3 4 [login] 5 username = test 6 password = 123456
读取ini文件的源码为:
1 # @Time : 2021/9/4 20:21 2 # @Author : '宫雪侠' 3 # @File : readCfg.py 4 import os 5 6 from configparser import ConfigParser 7 import os 8 9 class Readini(): 10 def __init__(self): 11 # 获取当前目录 12 current_dir = os.path.abspath('') 13 # 获取上一级目录 14 filePath = os.path.dirname(current_dir) 15 # 再获取上一级目录 16 lastFilePath = os.path.dirname(filePath) 17 # 拼接配置文件的路径 18 self.iniPath = os.path.join(lastFilePath, 'conf', 'readini.ini') 19 20 #默认获取主机的地址 21 def readCfg(self,section='hostname',option = 'host'): 22 #拼接配置文件的路径 23 con = ConfigParser() 24 con.read(self.iniPath,'utf-8') 25 res = con.get(section,option) 26 return res 27 28 #默认获取主机的地址 29 def getItems(self,section = 'login'): 30 #拼接配置文件的路径 31 con = ConfigParser() 32 con.read(self.iniPath,'utf-8') 33 res = con.items(section) 34 return dict(res) 35 36 if __name__ == '__main__': 37 readCfg = Readini().getItems()
读取txt文件源码:
# @Time : 2021/9/6 15:23 # @Author : '宫雪侠' # @File : readTxt.py import os class ReadTxt(): def __init__(self): # 再获取上一级目录 lastFilePath = os.path.dirname(os.path.abspath('')) # 拼接配置文件的路径 self.txtPath = os.path.join(lastFilePath, 'conf', 'text.txt') pass def readAllTxt(self): with open(self.txtPath,'r',encoding='utf-8') as f: text = f.read() return text def readoneLine(self): with open(self.txtPath,'r',encoding='utf-8') as f: # #读取一行 text1 = f.readline() return text1 def readLimtSize(self,size): with open(self.txtPath,'r',encoding='utf-8') as f: text1 = f.readline(size) return text1 def witeTxt(self): with open(self.txtPath,'w',encoding='utf-8') as f: f.write('我是中国人') #追加 def appendTxt(self): with open(self.txtPath,'a',encoding='utf-8') as f: f.write('我是中国人\n') if __name__ == '__main__': readTxt = ReadTxt() readTxt.appendTxt()