S. Bunyard
S. Bunyard

Reputation: 41

Using variable in file path in Python

I've found similar questions to this but can't find an exact answer and I'm having real difficulty getting this to work, so any help would be hugely appreciated.

I need to find a XML file in a folder structure that changes every time I run some automated tests.

This piece of code finds the file absolutely fine:

import xml.etree.ElementTree as ET
import glob

report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
print(report)

I get a path returned. I then want to use that path, in the variable "report" and look for text within the XML file.

The following code finds the text fine IF the python file is in the same directory as the XML file. However, I need the python file to reside in the parent file and pass the "report" variable into the first line of code below.

tree = ET.parse("JUnit_Report.xml")
root = tree.getroot()

for testcase in root.iter('testcase'):
    testname = testcase.get('name')
    teststatus = testcase.get('status')
    print(testname, teststatus)

I'm a real beginner at Python, is this even possible?

Upvotes: 2

Views: 656

Answers (1)

Psytho
Psytho

Reputation: 3384

Build the absolute path to your report file:

report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
abs_path_to_report = os.path.abspath(report)

Pass that variable to whatever you want:

tree = ET.parse(abs_path_to_report )

Upvotes: 2

Related Questions