python实现简单文件读写函数

作者:李子园的梦想 时间:2023-08-29 04:37:24 

python作为脚本性语言,加上它的简便易用性。会经常当作脚本用来处理一下数据和格式。其中处理文件就是频繁用处之一。简单编写几个常用的xls和txt读写函数,以后可以快速复用。

用到xlrd库函数需要预先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语句执行完毕后同时关闭打开的文件句柄。
ret = []
with open(txtFile, "r") as f:
for line in f.readlines():
line = line.strip('\n') # 去掉换行符
listInfo = line.split(sep) # 以 sep 分割成数组
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)

因文件中有中文,中间遇到中文乱码问题


import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# encoding="utf-8", ensure_ascii=False

1、这个是由于Unicode编码与ASCII编码的不兼容造成的。
2、通常都是ascii,由此Python自然调用ascii编码解码程序去处理字符流,当字符流不属于ascii范围内,就会抛出异常(ordinal not in range(128))

百度了下通过 以上方式 解决了。

来源:https://blog.csdn.net/heshushun/article/details/114001317

标签:python,文件读写
0
投稿

猜你喜欢

  • Python调用百度AI实现颜值评分功能

    2023-07-30 22:53:40
  • 深入浅出Golang中的sync.Pool

    2024-02-11 12:59:34
  • Go秒爬博客园100页新闻

    2024-04-26 17:15:49
  • javascript基础之数组(Array)对象

    2008-06-25 13:32:00
  • python3实现点餐系统

    2023-04-30 19:06:55
  • python中Pyqt5使用Qlabel标签进行视频播放

    2021-12-19 13:32:20
  • python中playwright结合pytest执行用例的实现

    2022-12-13 14:28:58
  • Python将阿拉伯数字转换为罗马数字的方法

    2022-11-15 16:07:14
  • python读取excel进行遍历/xlrd模块操作

    2022-11-09 18:44:51
  • Python中列表、字典、元组、集合数据结构整理

    2022-08-02 05:54:57
  • php巧获服务器端信息

    2023-10-04 02:18:39
  • 创建Django项目图文实例详解

    2021-06-12 23:09:30
  • 快速掌握JavaScript正则表达式

    2010-01-23 11:39:00
  • 关于浏览器的一些观点

    2008-08-06 12:48:00
  • 比较规范的验证Email地址是否正确的正则表达式

    2009-07-28 17:55:00
  • Mysql查询很慢卡在sending data的原因及解决思路讲解

    2024-01-18 02:40:45
  • Python Scrapy 框架简单介绍

    2021-09-18 14:51:48
  • python简单分割文件的方法

    2021-08-09 10:32:33
  • JavaScript中判断的优雅写法示例

    2024-04-10 10:43:46
  • python实现图片加文字水印OPenCV和PIL库

    2021-02-04 19:29:09
  • asp之家 网络编程 m.aspxhome.com