新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
通過(guò)python實(shí)現(xiàn)簡(jiǎn)單文件讀寫函數(shù)
python作為腳本性語(yǔ)言,加上它的簡(jiǎn)便易用性。會(huì)經(jīng)常當(dāng)作腳本用來(lái)處理一下數(shù)據(jù)和格式。其中處理文件就是頻繁用處之一。簡(jiǎn)單編寫幾個(gè)常用的xls和txt讀寫函數(shù),以后可以快速?gòu)?fù)用。

用到xlrd庫(kù)函數(shù)需要預(yù)先install
命令:pip install xlrd
直接貼源碼:
#! /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):
''' 寫入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)
因文件中有中文,中間遇到中文亂碼問(wèn)題
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# encoding="utf-8", ensure_ascii=False
1、這個(gè)是由于Unicode編碼與ASCII編碼的不兼容造成的。
2、通常都是ascii,由此Python自然調(diào)用ascii編碼解碼程序去處理字符流,當(dāng)字符流不屬于ascii范圍內(nèi),就會(huì)拋出異常(ordinal not in range(128))。
百度了下通過(guò) 以上方式 解決了,以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助
本文名稱:通過(guò)python實(shí)現(xiàn)簡(jiǎn)單文件讀寫函數(shù)
文章出自:http://m.fisionsoft.com.cn/article/ccojdso.html


咨詢
建站咨詢
