简体   繁体   English

Python 将 xml 转换为 csv,如何在我的 csv 文件中添加引号?

[英]Python converting xml to csv, how can I add quotation marks to my csv file?

The code parses through all the xml files in my folder and puts it all into one csv file.该代码解析了我文件夹中的所有 xml 文件,并将它们全部放入一个 csv 文件中。 However I would like to add quotes and not sure how to go about doing that.但是我想添加引号,但不知道如何去做。

output:输出:

image,width,height,xmin,ymin,xmax,ymax,name
image1.png,416,416,Dog,1995,848,2155,1075

What I actually want:我真正想要的是:

"image","width","height","xmin","ymin","xmax","ymax","name"
"image1.png",416,416,1995,848,2155,1075,"Dog"
import pandas as pd
import xml.etree.ElementTree as ET


def xml_to_csv(path):
    xml_list = []
    print(path)
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(member[4][1].text),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['image', 'width', 'height', 'name', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    for folder in ['train']:
        image_path = os.path.join(os.getcwd(), ('images/' + folder))
        xml_df = xml_to_csv(image_path)
        xml_df.to_csv(('images/' + folder + '_labels.csv'), index=None)
        print('Successfully converted xml to csv.')


main()

Add quoting=csv.QUOTE_NONNUMERIC .添加quoting=csv.QUOTE_NONNUMERIC Demo:演示:

import pandas as pd
import csv

column_name = ['image', 'width', 'height', 'name', 'xmin', 'ymin', 'xmax', 'ymax']
df = pd.DataFrame([["image1.png",416,416,1995,848,2155,1075,"Dog"]],columns=column_name)

df.to_csv('output.csv', index=None, quoting=csv.QUOTE_NONNUMERIC)

Output:输出:

"image","width","height","name","xmin","ymin","xmax","ymax"
"image1.png",416,416,1995,848,2155,1075,"Dog"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM