python 文件读写总结
2024-10-02 06:36:11
这是个人在项目中抽取的代码,自己写的utils的通用模块,使用的框架是tronado,包括了文件的读写操作,api格式的统一函数,如有特别需要可以联系我或者自己扩展,刚学python不久,仅供参考,例子如下。
import time
import json
import logging
import traceback
import codecs
import os conf_log = logging def resp_dict(data='', status="success", message="successful"):
"""return a dict format response"""
return dict(status=status, message=message, data=data, timestamp=time.time()) def read_json(filename):
# Load data from file
content = []
try:
conf_log.info("Reading input from file: " + str(filename))
if os.path.exists(filename):
with open(filename, "r") as fp:
content = json.load(fp)
else:
conf_log.warning("File %s does not exist." % filename) except Exception as e:
conf_log.error(e)
ex_str = traceback.format_exc()
conf_log.error(ex_str)
return content def read_json_config(filename, def_res):
# Load data from file
content = def_res
try:
conf_log.info("Reading input from file: " + str(filename))
if os.path.exists(filename):
with open(filename, "r") as fp:
content = json.load(fp)
else:
conf_log.warning("File %s does not exist." % filename) except Exception as e:
conf_log.error(e)
ex_str = traceback.format_exc()
conf_log.error(ex_str) return content def write_json(j_dict, file_name):
# Dump data into file
try:
conf_log.info("Writing file: " + str(file_name))
with codecs.open(file_name, "w", "utf-8") as outputFile:
json.dump(j_dict, outputFile, ensure_ascii=False, encoding="utf-8")
except Exception as e:
conf_log.error(e)
ex_str = traceback.format_exc()
conf_log.error(ex_str)
with codecs.open(file_name, "w", "utf-8") as outputFile:
outputFile.write(str(j_dict))
最新文章
- Python-4 变量、字符串
- ios开发xcode中设置代码块
- mina IoBuffer 常用方法
- BZOJ3540: [Usaco2014 Open]Fair Photography
- LeetCode Product of Array Except Self (除自身外序列之积)
- scala写算法-List、Stream、以及剑指Offer里部分题目基于scala解法
- 金融量化分析【day112】:量化交易策略基本框架
- 使用Protobuf定义网络协议
- 浏览器支持webp格式
- Java package can not import alias
- python 字符串内置方法实例
- Luogu4221 WC2018州区划分(状压dp+FWT)
- 用switch语句判断月份,打印出当前月份所在的季节
- 使用Akka构建集群(一)
- 在阿里云容器服务上开发基于Docker的Spring Cloud微服务应用
- 关于Cocos2d-x中实例伸缩后的位置设置
- 一致性哈希算法(consistent hashing)(转)
- Session的存储原理
- 复利计算C转java版
- Spring注解@ResponseBody,@RequestBody
热门文章
- 客服端JavaScript线程模型
- uni-app中vue组件父子值传递
- 敏捷开发中如何做好Sprint规划?
- 解码mmo游戏服务器三:大地图同步(aoi)
- 点菜网---Java开源生鲜电商平台-系统架构图(源码可下载)
- 跟我学SpringCloud | 第二篇:注册中心Eureka
- Hive —— 安装部署
- HBase 学习之路(十一)—— Spring/Spring Boot + Mybatis + Phoenix 整合
- String.format()
- 【Idea】JUnit单元测试%MODULE_WORKING_DIR%' does not exist