遍历文件夹找到某个时间段内的所有python
时间: 2024-10-20 10:09:42 浏览: 29
遍历文件夹并在特定时间段内查找Python文件通常涉及使用操作系统提供的API(如Python的os和datetime模块),以及对文件修改时间(mtime)的操作。以下是一个简单的Python脚本示例,它会搜索指定目录及其子目录,只保留那些在指定日期范围内的.py文件:
```python
import os
import datetime
def search_files_in_directory(directory, start_date, end_date):
matching_files = []
for root, _, files in os.walk(directory): # 遍历目录树
for file in files:
if file.endswith('.py'): # 只检查Python文件
file_path = os.path.join(root, file)
file_mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
# 检查文件是否在指定日期范围内
if start_date <= file_mtime <= end_date:
matching_files.append(file_path)
return matching_files
# 使用示例
start_date_str = '2023-01-01'
end_date_str = '2023-01-31'
start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d')
end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d')
directory_to_search = '/path/to/your/directory'
result_files = search_files_in_directory(directory_to_search, start_date, end_date)
阅读全文