当文件名字包含指定的文字 且 名字中的时间序列号为最新的时候我们读取他
时间: 2024-03-23 15:36:07 浏览: 7
你可以使用Python的`os`和`re`模块来实现这个功能。以下是一个示例代码:
```python
import os
import re
dir_path = "/path/to/files" # 文件夹路径
text_to_find = "example" # 要查找的文字
# 获取指定文件夹下的所有文件列表
files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
# 定义一个变量来保存最新的文件名和时间戳
latest_file = None
latest_time = 0
# 遍历所有文件
for file in files:
# 如果文件名中包含指定的文字
if text_to_find in file:
# 使用正则表达式从文件名中提取时间戳
match = re.search(r"\d{8}", file)
if match:
# 获取时间戳并转换为整数
time_str = match.group()
time_int = int(time_str)
# 如果比最新的时间戳还要新,则更新最新的文件名和时间戳
if time_int > latest_time:
latest_file = file
latest_time = time_int
# 如果找到了最新的文件,则打开它
if latest_file:
file_path = os.path.join(dir_path, latest_file)
with open(file_path, "r") as f:
content = f.read()
print(content)
else:
print("No matching file found.")
```
在这个示例代码中,我们首先获取指定文件夹下的所有文件列表。然后,我们遍历每个文件,如果文件名中包含指定的文字,就使用正则表达式从文件名中提取时间戳,并将其转换为整数。如果时间戳比最新的时间戳还要新,则更新最新的文件名和时间戳。最后,如果找到了最新的文件,则使用`open()`函数打开它并读取文件内容。如果没有找到匹配的文件,则输出一条消息。