• Python读取文件基本方法


    在日常开发过程中,经常遇到需要读取配置文件,这边就涉及到一个文本读取的方法。

    这篇文章主要以Python读取文本的基础方法为本,添加读取整篇文本返回字符串,读取键值对返回字典,以及读取各个项返回列表的应用。至于读取xml文件或者加密文件的其他方法这里不做介绍,后续会详细讲解。

    这里直接上模块案例,可以看到 此类中含有3个读取文件的方法,且返回值分别为str,dict,list,分别应用于不同的场景下。其中读取方式都是一样的,分享这个类的目的就是为了让熟手们不用再在代码中写啦,直接引用这个包就行啦!

    代码中也融合了一些之前学习的知识点,包括默认参数,冒号与箭头的含义等~

     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('
    ', '').replace('
    ', '').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('
    ', '').replace('
    ', ''))
    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=1651984111360013

  • 相关阅读:
    富文本 文字图片点击,(TextView)
    swift和oc之间的相互调用(block,代理)
    SVN .a文件丢失问题
    URL Schemes 不能识别和不能跳转的原因
    tableViewcell上放定时器
    app之间的跳转和传参问题
    dicom通讯的工作方式及dicom标准简介
    Dicom格式文件解析器
    消息队列
    c#高级编程第七版 学习笔记 第一章 .NET体系结构
  • 原文地址:https://www.cnblogs.com/potato-find/p/13216471.html
Copyright © 2020-2023  润新知