python parse_xml_csv.py
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python parse_xml_csv.py相关的知识,希望对你有一定的参考价值。
import os
import sys
import argparse
try:
import xml.etree.ElementTree as etree
except Exception:
print()
print("lxml , module Not Found")
print("Install: pip install lxml")
sys.exit(1)
try:
import unicodecsv as csv
except Exception:
print()
print("unicodecsv , module Not Found")
print("Install: pip install unicodecsv")
sys.exit(1)
parser = argparse.ArgumentParser(
description='Converte XML para CSV - Mantis Geobit')
parser.add_argument('path', help='Path of xml file')
parser.add_argument(
'-d', action='store', dest='destiny', help='Destiny of csv file')
options = parser.parse_args()
def main():
xml_path = options.path
if options.destiny:
csv_path = options.destiny
else:
xml_fname = os.path.basename(xml_path)
csv_path = os.path.join(
os.path.dirname(xml_path), os.path.splitext(xml_fname)[0] + ".csv")
try:
os.remove(csv_path)
except OSError:
pass
tree = etree.parse(xml_path)
root = tree.getroot()
els = []
for child in root:
report = child.find('reporter').text
id_el = child.find('id').text
handler = child.find('handler')
if hasattr(handler, 'text'):
handler = handler.text
else:
handler = ''
summary = child.find('summary').text
horas = '0'
for it in child.find('custom_fields').iter('custom_field'):
if it.find('id').text == '1':
horas = it.find('value').text
els.append((report, handler, id_el, summary, horas))
with open(csv_path, "wb") as csv_file:
writer = writer = csv.writer(
csv_file, dialect='excel', delimiter=";", encoding="utf-8-sig")
writer.writerow(['reportou', 'admitiu', 'id', 'demanda', 'horas'])
for line in els:
writer.writerow(line)
if __name__ == "__main__":
main()
以上是关于python parse_xml_csv.py的主要内容,如果未能解决你的问题,请参考以下文章
001--python全栈--基础知识--python安装
Python代写,Python作业代写,代写Python,代做Python
Python开发
Python,python,python
Python 介绍
Python学习之认识python