2017-11-16 5 views
0

次のコードは、すべてのフォルダ、サブフォルダ、およびファイルのデータを、それぞれのサイズとともに示しています。現在、これはデータをCSVファイルに保存しています。しかし、私はこの種のデータ(ネストされたデータ)がXMLに最も適していると信じています。私はXMLに精通していません。コードを変更するすべてのヘルプはあなたが出力XMLファイルを作成するために、インポートxml.etree.ElementTreeの助けを借りることができます出力ファイルをXML形式にするためのPythonコードの変更

import os 
import csv 

def GetHumanReadable(size,precision=2): 
    suffixes=['KB','MB','GB','TB'] 
    suffixIndex = 0 
    while size > 1024: 
     suffixIndex += 1 #increment the index of the suffix 
     size = size/1024.0 #apply the division 
    return "%.*f %s"%(precision,size,suffixes[suffixIndex]) 

def list_files(startpath): 
    with open('output.csv','w') as file: 
     for root, dirs, files in os.walk(startpath): 
      level = root.replace(startpath, '').count(os.sep) 
      indent = ' ,' * 4 * (level) 
      file.write('{}{}/\n'.format(indent, os.path.basename(root))) 
      subindent = ' ,' * 4 * (level + 1) 
      for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)): 
       converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f)) 
       file.write('{}{},{}\n'.format(subindent, f, converted_size)) 
+0

は(https://docs.python.org/3/library/xml.etree.elementtree.html)xml.etree.elementtree]を使用しようとします –

答えて

0

を理解されるであろう。ここで は一例で

import xml.etree.ElementTree as ET 
data=''' 
<root> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The quick</F> 
    <F LV="1">brown</F> 
    <F LV="2">fox</F> 
</FC> 
</H> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The lazy</F> 
    <F LV="1">fox</F> 
</FC> 
</H> 
</root> 
''' 
root= ET.XML(data) 

with open('d:\output.xml', 'wb') as file: 
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True) 
関連する問題