Python讀取文件基本方法

在平常開發過程當中,常常遇到須要讀取配置文件,這邊就涉及到一個文本讀取的方法。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

相關文章
相關標籤/搜索