Skip to content
Advertisement

Is there a possibility in python to output column values as file names?

I have the following df:

In [1]: df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

In [2]: df
Out[2]: 
   A  B
0  1  2
1  1  3
2  4  6

Now I want to output column A values as file names.

fac_doc_template = XML

fac_details_xml_template = {A} 
{B}

#formatting
def series_to_fac_details_xml(s):
    return fac_details_xml_template.format(**s)


#for loop to output file as index names
for index, row in df.iterrows():
    details = series_to_fac_details_xml(row)
    with open(fr"C:UsersMax12DesktopxmlpdfminerUiPathoutput{index}.xml", "w") as f:
        f.write(fac_doc_template.format(fac_details=details))

My output now is: 0.xml, 1.xml, 2.xml.

However I would like my output files to be the following:

1.xml, 1.xml, 4.xml.

Can you help me?

Advertisement

Answer

Use the 'A' value from the row, so:

#for loop to output file as index names
for index, row in df.iterrows():
    details = series_to_fac_details_xml(row)
    with open(fr"C:UsersMax12DesktopxmlpdfminerUiPathoutput{row['A']}.xml", "w") as f:
        f.write(fac_doc_template.format(fac_details=details))
Advertisement