[英]How to store most recent file path as a variable and then read it in python
免责声明:我对 Python 非常陌生,但我喜欢参与一个项目。
我想要做的是为我的元组中的每个元素搜索一个文件夹,并为每个元素打开最新的文件(这是一个 xml 文件)。 然后在该文件中搜索失败并通过的字符串。 如果文件包含超过 2 个失败/通过,则返回 true 或 false。
在 python 使用 new_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')
看起来您正在传递字符串'newest_file_path'
,而不是变量,并且还获取日期而不是路径。 试试这样:
...
newest_file_path = file_date[0][0]
with open(newest_file_path) as p:
...
因为zip(TestResults, mod_dates)
将目录作为第 0 个索引,将日期作为第一个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.