Search code examples
python-3.xxmlpandasdataframepython-itertools

How to create unique XML for each row of dataframe in Python


I have dataframe like below.

df3.head(5)

ORDER      STS_CODE   Date
20200210285112  117      2030-12-31
20200210285112  300      2020-02-18
20200210285104  300      2020-02-20
20200210285101  400      2020-02-16
20200210285100  500      2030-02-19

I want create distinct XML for each record in the df3 in the below format ORDER_STS_CODE.xml( eg. 20200210285100_500.xml)

My current code is only able create only one single xml with all records attached inside it.

Current Code

head ="""
<?xml version="1.0" encoding="UTF-8"?>
<hdr:MSGHDR>

<VERNUM>0100</VERNUM>

<CREDTM>{0}</CREDTM>

</hdr:MSGHDR>
"""

body ="""
<ord:ORD>

<ORDKEY>{}</ORDKEY>

<ORDTYP>TO</ORDTYP>

<osi:ORDSTSINF types:STSCDE="{}">

<DTM>{}</DTM>

</osi:ORDSTSINF>

</ord:ORD>
"""
footer = """</ilsord:ILSORD>
"""
from datetime import datetime
import time
df3 = pd.read_csv('XML1.csv')
df3.drop(df3.filter(regex="Unnamed"),axis=1, inplace=True)
glogdate = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

with open('Test.xml', 'w') as f:
    f.write(head.format(glogdate))
    for row in df3.itertuples():
       f.write(body.format(row[1], row[2], row[3]))
    f.write(footer)

What should I do inside current code to create distinct Xml from dataframe ?


Solution

  • You can stick to your itertuples if you prefer. All you need to do is to create the file inside your loop.

    for row in df3.itertuples():
        with open(f'{row[1]}_{row[2]}.xml', 'w') as f:
            f.write(head.format(glogdate))
            f.write(body.format(row[1], row[2], row[3]))
            f.write(footer)