Python 提取dict转换为xml/json/table并输出的实现代码

yipeiwu_com5年前Python基础

核心代码:

#!/usr/bin/python
#-*- coding:gbk -*-
#设置源文件输出格式
import sys
import getopt
import json
import createDict
import myConToXML
import myConToTable
 
 
def getRsDataToDict():
  #获取控制台中输入的参数,并根据参数找到源文件获取源数据
  csDict={}
  try:
    #通过getopt获取参数
    opts,args=getopt.getopt(sys.argv[1:],"",["output=","file=","query="])
    csDict=createDict.procParam(opts,args)
    return csDict
  except getopt.GetoptError:
    print getopt.error
    sys.exit()
 
def collectionToJson(contentTxt):
  #参数1表示python对象;参数2表示按照字典排序;参数3表示根据格式缩进显示
  jsoninfo = json.dumps(contentTxt,sort_keys=True,indent=2)
  print "JSON输出:"
  print type(jsoninfo)
  print jsoninfo
 
if __name__=="__main__":
  #输入参数格式为>python test.py output=json file=c:\..\input.txt query=Permission[0]
  inputParm=getRsDataToDict()
  if inputParm["query"]!=None:
    csDict=createDict.getQueryRs(inputParm["contentTxt"],inputParm["query"])
  else:
    csDict=inputParm["contentTxt"]
  output=inputParm["output"]
  if output=="json":
    collectionToJson(csDict)
  elif output=="xml":
    path='C:\\Users\\Vincent\\Documents\\MyTest1.xml'
    encod='utf8'
    myConToXML.getDictToXml(csDict,path,encod)
  elif output=="table":
    myConToTable.ContentToTable(csDict)

相关文章

Python之自动获取公网IP的实例讲解

Python之自动获取公网IP的实例讲解

0.预备知识 0.1 SQL基础 ubuntu、Debian系列安装: root@raspberrypi:~/python-script# apt-get install mysql...

Python装饰器原理与基本用法分析

本文实例讲述了Python装饰器原理与基本用法。分享给大家供大家参考,具体如下: 装饰器: 意义:在不能改变原函数的源代码,和在不改变整个项目中原函数的调用方式的情况下,给函数添加新的功...

python 调用有道api接口的方法

python 调用有道api接口的方法

初学python ,研究了几天,写了一个python 调用 有道api接口程序 效果看下图: 申明:代码仅供和我一样的初学者学习交流 有道api申请地址http://fanyi.you...

Python模块学习 filecmp 文件比较

filecmp定义了两个函数,用于方便地比较文件与文件夹: filecmp.cmp(f1, f2[, shallow]): 比较两个文件的内容是否匹配。参数f1, f2指定要比较的文件的...

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

概述 见源码 源码 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 图片(文件)下载,核心方法是 urllib.urlre...