This article mainly introduces Python to implement simple file reading and writing functions in detail. The sample code in the article is very detailed and has certain reference value. Interested friends can refer to it. |
Python is a scripting language, plus its ease of use. It is often used as a script to process data and format. Among them, processing files is one of the frequent uses. Simply write a few commonly used xls and txt read and write functions, which can be quickly reused in the future.
Use of xlrd library functions need to be installed in advance
Command : pip install xlrd
Paste the source code directly:
#! /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): ''' 读取xls文件生成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 to generate 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 the txt file ''' # with + open can guarantee the completion of the with statement Then close the open file handle at the same time. ret = [] with open(txtFile, "r") as f: for line in f.readlines(): line = line.strip('\n') # Remove line breaks listInfo = line. return ret @classmethod def writeToJson(cls, jsonFile, ret): ''' 写入json文件 ''' 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写入文件 ''' with open(filePath, 'w') as fp: fp.write(s) @classmethod def writeFromList(cls, filePath, wList): ''' list写入文件 ''' 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, Chinese garbled characters are encountered
import sys reload(sys) sys.setdefaultencoding('utf-8') # encoding="utf-8", ensure_ascii=False
1. This is caused by the incompatibility between Unicode encoding and ASCII encoding.
2. It is usually ascii, so Python naturally calls the ascii encoding and decoding program to process the character stream. When the character stream does not belong to the ascii range, it will throw an exception (ordinal not in range(128)).
Baidu has solved it through the above methods. The above is the entire content of this article. I hope it will be helpful to everyone's learning.