在平常开发过程当中,常常遇到须要读取配置文件,这边就涉及到一个文本读取的方法。html
这篇文章主要以Python读取文本的基础方法为本,添加读取整篇文本返回字符串,读取键值对返回字典,以及读取各个项返回列表的应用。至于读取xml文件或者加密文件的其余方法这里不作介绍,后续会详细讲解。python
这里直接上模块案例,能够看到 此类中含有3个读取文件的方法,且返回值分别为str,dict,list,分别应用于不一样的场景下。其中读取方式都是同样的,分享这个类的目的就是为了让熟手们不用再在代码中写啦,直接引用这个包就行啦!app
代码中也融合了一些以前学习的知识点,包括默认参数,冒号与箭头的含义等~学习
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 """ 5 根据不一样的读取文件的目的,返回不一样的数据类型 6 能够返回str, dict, list 7 """ 8 9 10 class FileOperation(object): 11 12 def __init__(self, filepath, filename): 13 self.files = filepath + filename 14 15 16 ''' 将全文本读取出来返回一个字符串,并包含各类转行符 ''' 17 def readFile(self) -> str: 18 res = '' 19 f = open(self.files, 'r', encoding='utf-8') 20 for line in f: 21 res += line 22 f.close() 23 return res 24 25 26 ''' 针对键值对形式的文本,逐个读取存入到字典中,返回一个字典类型数据,经常使用于配置文件中 ''' 27 def readFile2Dict(self, sp_char = '=') -> dict: 28 res = {} 29 f = open(self.files, 'r', encoding='utf-8') 30 for line in f: 31 (k,v) = line.replace('\n', '').replace('\r', '').split(sp_char) 32 res[k] = v 33 f.close() 34 return res 35 36 37 ''' 针对须要逐行放入列表中的文本,返回一个列表类型 ''' 38 def readFile2List(self) -> list: 39 res = [] 40 f = open(self.files, 'r', encoding='utf-8') 41 for line in f: 42 res.append(line.replace('\n', '').replace('\r', '')) 43 f.close() 44 return res 45 46 47 if __name__ == '__main__' : 48 import os 49 50 fo = FileOperation(os.getcwd() + '\\temp\\', 'model.html') 51 res = fo.readFile() 52 print(res) 53 54 55 fo = FileOperation(os.getcwd() + '\\temp\\', 'test.txt') 56 res = fo.readFile2Dict('|') 57 print(res) 58 59 60 fo = FileOperation(os.getcwd() + '\\temp\\', 'test.txt') 61 res = fo.readFile2List() 62 print(res)
今天就分享这个简单的案例,若有其余场景需求,评论或私信我,都会加以改进,分享到这里的,另外特殊文件的读取和写入,我会在后期也一并分享,关注我,后期整理不能少!加密
或者关注我头条号,更多内容等你来 https://www.toutiao.com/c/user/3792525494/#mid=1651984111360013spa