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()
