python作為腳本性語(yǔ)言,加上它的簡(jiǎn)便易用性。會(huì)經(jīng)常當(dāng)作腳本用來(lái)處理一下數(shù)據(jù)和格式。其中處理文件就是頻繁用處之一。簡(jiǎn)單編寫(xiě)幾個(gè)常用的xls和txt讀寫(xiě)函數(shù),以后可以快速?gòu)?fù)用。
#! /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):
'''
讀取xls文件生成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):
'''
讀取txt文件
'''
# with + open 可保證with語(yǔ)句執(zhí)行完畢后同時(shí)關(guān)閉打開(kāi)的文件句柄。
ret = []
with open(txtFile, "r") as f:
for line in f.readlines():
line = line.strip('\n') # 去掉換行符
listInfo = line.split(sep) # 以 sep 分割成數(shù)組
if listInfo:
ret.append(listInfo)
return ret
@classmethod
def writeToJson(cls, jsonFile, ret):
'''
寫(xiě)入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寫(xiě)入文件
'''
with open(filePath, 'w') as fp:
fp.write(s)
@classmethod
def writeFromList(cls, filePath, wList):
'''
list寫(xiě)入文件
'''
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)