Adding file name in the output file

Viewed 33

I'm using the following code to read data from xml and to write data in stata (.dta) format. For each XML, I want to add file names to the output as well. Can you suggest any changes to my code so that I can have the file name in the output?

financials = {"id": ["Header/id/text()"]} # there are few more variables in the list

files = glob.glob(path + "/*.xml")
list = []

for file in files:
    tree = etree.parse(file)
    root = tree.getroot()

    # building list per xml
    s_temp = []
    for item in financials:
        s_temp.append(choose_xpath(root, financials[item]))
    list.append(s_temp)

# Building data frame from the collected data from all the xmls
s_df = pd.DataFrame(list, columns=list(financials.keys()))
s_df.to_stata("List.dta")
1 Answers

glob returns a list of filepaths. Using os.path.basename gets you only the filename. then start your list with it:

from os.path import basename

# building list per xml
s_temp = [basename(file)] # filename
Related