简体   繁体   English

如何将最近的文件路径存储为变量,然后在 python 中读取它

[英]How to store most recent file path as a variable and then read it in python

Disclaimer: I am very new to Python but I love to jump in to a project.免责声明:我对 Python 非常陌生,但我喜欢参与一个项目。

What I am trying to do is search a folder for each element in my tuple and for each element, open the most recent file (which is an xml file).我想要做的是为我的元组中的每个元素搜索一个文件夹,并为每个元素打开最新的文件(这是一个 xml 文件)。 Then search that file for the strings failed and passed.然后在该文件中搜索失败并通过的字符串。 And then return either true or false if the file contained more than 2 of either failed/passed.如果文件包含超过 2 个失败/通过,则返回 true 或 false。

I'm having a hard time figuring out how to open the most recent file after python finds it with the new_file_path variable.在 python 使用 new_file_path 变量找到它之后,我很难弄清楚如何打开最新的文件。 I get: FileNotFoundError: [Errno 2] No such file or directory: 'newest_file_path'我得到: FileNotFoundError:[Errno 2] 没有这样的文件或目录:'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')

Looks like you're passing the string, 'newest_file_path' , instead of the variable, and also grabbing the date rather than the path.看起来您正在传递字符串'newest_file_path' ,而不是变量,并且还获取日期而不是路径。 Try like this:试试这样:

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

Because zip(TestResults, mod_dates) puts the directories as the 0th index, and the dates as the 1st index.因为zip(TestResults, mod_dates)将目录作为第 0 个索引,将日期作为第一个索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM