【问题标题】:Python code modification to make output file as XML and not CSVPython 代码修改以使输出文件为 XML 而不是 CSV
【发布时间】:2017-11-16 22:42:42
【问题描述】:

以下代码为我提供了所有文件夹、子文件夹和文件的数据以及每个文件的大小。目前,这是将数据保存在 CSV 文件中。但我相信这种数据(嵌套数据)最适合 XML。我不太精通 XML。任何修改代码的帮助将不胜感激

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))

【问题讨论】:

标签: python xml csv


【解决方案1】:

您可以借助 import xml.etree.ElementTree 来制作输出 xml 文件。 这是一个例子

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)

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 2023-04-09
    • 2012-06-12
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多