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))
原文地址:https://www.cnblogs.com/jingtyu/p/6911343.html