在Python的文件路径中使用变量

时间:2018-11-26 16:32:37

标签: python

我已经找到了与此类似的问题,但是找不到确切的答案,而且我很难使它正常工作,因此任何帮助将不胜感激。

我需要在文件夹结构中找到一个XML文件,该文件在每次运行一些自动化测试时都会改变。

这段代码绝对可以找到文件:

db.executeSql('INSERT INTO Apikeys(ApiKey,ApiName) VALUES(?,?)', [key, name])
            .then(() => {
              db.executeSql('SELECT * FROM Apikeys', [])
                .then(res => {
                  if (res.rows.length > 0) {
                    console.log(res.rows.item(0).Id);
                    console.log(res.rows.item(0).ApiKey);
                    console.log(res.rows.item(0).ApiName);
                  }
                })
                .catch(e => {
                  console.log(e);
                });
            }).catch(e => {
              e => console.log(e)
            });

我得到一条返回的路径。然后,我想在变量“ report”中使用该路径,并在XML文件中查找文本。

如果python文件与XML文件位于同一目录中,则以下代码可以很好地查找文本。但是,我需要将python文件放置在父文件中,并将“报告”变量传递到下面的第一行代码中。

import xml.etree.ElementTree as ET
import glob

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

我是Python的真正初学者,这有可能吗?

1 个答案:

答案 0 :(得分:2)

构建报告文件的绝对路径:

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

将该变量传递给您想要的任何内容:

tree = ET.parse(abs_path_to_report )