【问题标题】:How to store most recent file path as a variable and then read it in python如何将最近的文件路径存储为变量,然后在 python 中读取它
【发布时间】:2021-03-17 17:00:16
【问题描述】:

免责声明:我对 Python 很陌生,但我喜欢参与一个项目。

我要做的是为我的元组中的每个元素搜索一个文件夹,并为每个元素打开最新的文件(这是一个 xml 文件)。然后在该文件中搜索失败并通过的字符串。如果文件包含超过 2 个失败/通过,则返回 true 或 false。

在 python 使用 new_file_path 变量找到最新文件后,我很难弄清楚如何打开它。 我得到: FileNotFoundError: [Errno 2] No such file or directory: 'newest_file_path'

import os
import glob
KeyWord = ("failed", "passed")
SNtup = ('5241', '4784', '4698')
TestResults = 'C:/Users/blah/blah'
for i in os.listdir(TestResults):
for x in SNtup:
        # glob.glob returns all paths matching the pattern.
        TestResults = list(glob.glob(os.path.join(TestResults, '*.XML*')))
        mod_dates = [os.path.getmtime(f) for f in TestResults]
        #sort by mod_dates.
        file_date = sorted(zip(TestResults, mod_dates), key=lambda d: d[1])
        newest_file_path = file_date[0][1]
        with open('newest_file_path') as p:
            file_content = p.read()
            for y in KeyWord:
                if y > 2 in file_content:
                    print('True')
                else:
                    print('False')

【问题讨论】:

    标签: python xml file path


    【解决方案1】:

    看起来您传递的是字符串'newest_file_path',而不是变量,并且还获取了日期而不是路径。试试这样:

    ...
            newest_file_path = file_date[0][0]
            with open(newest_file_path) as p:
    ...
    

    因为zip(TestResults, mod_dates) 将目录作为第 0 个索引,将日期作为第一个索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多