Realization of simple file reading and writing function by python

  • 2021-09-11 20:44:55
  • OfStack

python as a scripting language, plus its ease of use. It is often used as a script to deal with data and format under 1. Among them, processing documents is one of the frequent uses. Simply write several commonly used xls and txt read-write functions, which can be quickly reused in the future.

To use xlrd library functions, install is required in advance

Command: pip install xlrd

Direct paste source code:


#! /usr/bin/python
# coding:utf-8
 
import json
import xlrd
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
 
class ObjectFileReadAndWrite(object):
 
 @classmethod
 def readXlsToDict(cls, xlsFile):
 '''
  Read xls File generation dict
 '''
 data = xlrd.open_workbook(xlsFile)
 table = data.sheet_by_index(0)
 ret = []
 keys = table.row_values(0)
 for rowNum in range(table.nrows):
 oneRowValues = table.row_values(rowNum)
 if rowNum > 0:
 d = {}
 for colIdx, key in enumerate(keys):
 d[key] = oneRowValues[colIdx]
 ret.append(d)
 return ret
 
 @classmethod
 def readXlsToList(cls, xlsFile):
 '''
  Read xls File generation list
 '''
 data = xlrd.open_workbook(xlsFile)
 table = data.sheet_by_index(0)
 ret = []
 for rowNum in range(table.nrows):
 oneRowValues = table.row_values(rowNum)
 ret.append(oneRowValues)
 return ret
 
 @classmethod
 def readTxt(cls, txtFile, sep):
 '''
  Read txt Documents 
 '''
 # with + open  Guaranteeable with Close the open file handle at the same time after the statement is executed. 
 ret = []
 with open(txtFile, "r") as f:
 for line in f.readlines():
 line = line.strip('\n') #  Remove the line break 
 listInfo = line.split(sep) #  With  sep  Split into arrays 
 if listInfo:
 ret.append(listInfo)
 return ret
 
 @classmethod
 def writeToJson(cls, jsonFile, ret):
 '''
  Write json Documents 
 '''
 with open(jsonFile, 'w') as fp:
 json.dump(ret, fp, indent=2, sort_keys=True, encoding="utf-8", ensure_ascii=False)
 
 @classmethod
 def writeFromStr(cls, filePath, s):
 '''
 string Write to a file 
 '''
 with open(filePath, 'w') as fp:
 fp.write(s)
 
 @classmethod
 def writeFromList(cls, filePath, wList):
 '''
 list Write to a file 
 '''
 with open(filePath, 'w') as fp:
 fp.writelines(wList)
 
 
if __name__ == "__main__":
 obj = ObjectFileReadAndWrite()
 # xls
 ret = obj.readXlsToDict(xlsFile='xxx.xls')
 obj.writeToJson('xxx.json', ret)
 # txt
 ret2 = obj.readTxt(txtFile='result.txt', sep=" ")
 obj.writeToJson('result.json', ret2)

Because there is Chinese in the file, there is a problem of Chinese garbled code in the middle


import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
 
# encoding="utf-8", ensure_ascii=False

1. This is due to the incompatibility between Unicode encoding and ASCII encoding.
2. It is usually ascii, so Python naturally calls ascii encoding and decoding program to process the character stream. When the character stream does not belong to ascii, an exception will be thrown (ordinal not in range (128))

Baidu solved it in the above way.


Related articles: