澳门新蒲京娱乐

新蒲京官方下载 1
不会重叠

在Linux系统桌面添加漂亮的日历,给Linux桌面添加漂亮的日历

Python实现简单的多任务mysql转xml的方法,Xml文件添加字节属性的方法【新蒲京官方下载】

实例如下所示:

本文实例讲述了Python实现简单的多任务mysql转xml的方法。分享给大家供大家参考,具体如下:

from xml.etree.cElementTree import ElementTree,Element
import xlrd
import re
def read_xlsx(xlsx_path):
  workbook = xlrd.open_workbook(xlsx_path)
  booksheet = workbook.sheet_by_name("Sheet1")
  p = list()
  row_data = []
  for row in range(booksheet.nrows):
    for col in range(booksheet.ncols):
      cel = booksheet.cell(row, col)
      val = cel.value
      try:
        val = cel.value
        val = re.sub(r'\s+', '', val)
      except:
        pass
      if type(val) == float:
        val = int(val)
      else:
        val = str(val)
      row_data.append(val)
  p.append(row_data)
  return p
def read_xml(Int_path):
  tree = ElementTree()
  tree.parse(Int_path)
  return tree
def write_xml(tree, out_path):
  tree.write(out_path,encoding="utf-8",xml_declaration=True)
  '''tree.write('output.xml')'''
def if_match(node,k_name,k_val):
  c = node.get(k_name)
  if node.get(k_name) == k_val:
    return True
  return False
def find_nodes(tree,path):
  return tree.findall(path)
def get_node_by_keyvalue(nodelist,key_name,key_val):
  result_nodes=[]
  for node in nodelist:
    if if_match(node,key_name,key_val):
      result_nodes.append(node)
  return result_nodes
def add_node_properties(nodelist,add_key,add_properties):
  for node in nodelist:
    node.set(add_key,add_properties)
  return node
if __name__ == "__main__":
  tree = read_xml("./ContentList.xml")
  nodes = find_nodes(tree,"Content")
  P = read_xlsx("./ServiceId.xlsx")
  a = P[0]
  i = 0
  while i < 80:
    result_nodes = get_node_by_keyvalue(nodes , "AssetId" , a[i])
    add_node_properties(result_nodes,"ServiceId",a[i+1])
    i = i + 2
  write_xml(tree,'./ContentList1.xml')

为了需求导出的格式尽量和navicat导出的xml一致。

以上这篇Python
Xml文件添加字节属性的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

用的gevent,文件i/o操作会阻塞,所以并不会完全异步。

您可能感兴趣的文章:

  • python操作xml文件详细介绍
  • Python 解析XML文件
  • python写入xml文件的方法
  • Python中使用dom模块生成XML文件示例
  • 详解 Python
    读写XML文件的实例
  • python解析xml文件实例分享
  • Python创建xml文件示例
  • python操作xml文件示例
  • python处理xml文件的方法小结
  • 利用python将xml文件解析成html文件的实现方法
  • Python实现的读取/更改/写入xml文件操作示例
  1. mysql2xml.py:
# -*- coding: utf-8 -*-
'''
Created on 2014/12/27
@author: Yoki
'''
import gevent
import pymysql
from pymysql.cursors import DictCursor
import re
import codecs
db_conn = None
def init_mysql_connect(*args, **kwargs):
  global db_conn
  db_conn = pymysql.connect(*args, **kwargs)
def list_to_xml(result_cur, key_list):
  '''
  mysql 结果集转xml,非xml标准导出方式; xml dom 不支持相同名字的node
  :param result_cur:
  :param key_list:
  :return:
  '''
  content = ''
  content += '<?xml version="1.0" encoding="UTF-8" ?>\r\n'
  content += '<RECORDS>\r\n' # root节点
  for item in result_cur:
    content += '\t<RECORD>\r\n'
    for k in key_list:
      v = item.get(k, '')
      real_value = v
      content += '\t\t<%s>%s</%s>\r\n' % (k, real_value, k)
    content += '\t</RECORD>\r\n'
  content += '</RECORDS>\r\n'
  return content
def get_table_rows(tb_name):
  '''
  获取mysql表rows
  :param tb_name:
  :return:
  '''
  global db_conn
  rows = []
  cursor = db_conn.cursor(cursor=DictCursor)
  cursor.execute('select * from %s' % tb_name)
  for row in cursor:
    rows.append(row)
  return rows
def get_table_keys(tb_name):
  '''
  获取表中字段,顺序 为创建表时的顺序
  :param tb_name:
  :return:
  '''
  global db_conn
  cursor = db_conn.cursor(cursor=DictCursor)
  cur = cursor.execute('show create table %s' % tb_name)
  if cur != 1:
    raise Exception
  for r in cursor:
    create_sql = r['Create Table']
    fields = re.findall('`(.*?)`', create_sql)
    result = []
    # 处理字段
    for i in xrange(1, len(fields)):
      field = fields[i]
      if field in result:
        continue
      result.append(field)
    return result
  return []
def mysql_to_xml(tb_name, output_dir='xml', postfix='xml'):
  '''
  mysql数据导出xml,
  :param tb_name: 数据库表名
  :param output_dir:
  :param postfix:
  :return:
  '''
  rows = get_table_rows(tb_name)
  keys = get_table_keys(tb_name)
  content = list_to_xml(rows, keys)
  fp = codecs.open('%s/%s.%s' % (output_dir, tb_name, postfix), 'w', 'utf-8')
  fp.write(content)
  fp.close()
tb_list = [
  'tb_item',
  'tb_state'
]
if __name__ == '__main__':
  init_mysql_connect(host="localhost", user='user', password="password", database='test', port=3306,
            charset='utf8')
  jobs = []
  for tb_name in tb_list:
    jobs.append(gevent.spawn(mysql_to_xml, tb_name))
  gevent.joinall(jobs)

相关文章

No Comments, Be The First!
近期评论
    功能
    网站地图xml地图