zoukankan      html  css  js  c++  java
  • python 文件读写总结

    这是个人在项目中抽取的代码,自己写的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))
  • 相关阅读:
    PHP7革新与性能优化
    git团队开发
    PHP获取机器mac代码
    js复制文字
    jquery datatable客户端分页保持
    自已编写C# DLL 绑定到unity进程进行单步调试
    ‘xxfile' Missing the class attribute 'ExtensionOfNativeClass'
    关于热更的杂记
    关于unityengine.dll, unityengine.coremodule.dll
    学到了关于服务器磁盘阵列
  • 原文地址:https://www.cnblogs.com/jingtyu/p/6911343.html
Copyright © 2011-2022 走看看