Python每2分钟从一个路径下多级文件夹中找到当天建立的txt文件,并合并成一个txt文本到另一个路径中
时间: 2024-05-12 17:20:04 浏览: 11
以下是Python代码示例,可以实现从指定路径下找到当天创建的所有txt文件,并将其合并成一个txt文件保存到另一个指定路径下:
```python
import os
import datetime
# 指定要查找的路径和保存结果的路径
search_path = 'path/to/search'
result_path = 'path/to/result.txt'
# 获取当前日期,并设置文件名格式
today = datetime.datetime.now().strftime('%Y-%m-%d')
# 遍历指定路径下所有文件和文件夹
for root, dirs, files in os.walk(search_path):
# 遍历所有文件
for file in files:
# 如果文件是txt文件且创建日期是当天
if file.endswith('.txt'):
file_path = os.path.join(root, file)
create_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y-%m-%d')
if create_time == today:
# 将符合条件的文件内容合并到结果文件中
with open(file_path, 'r') as f:
with open(result_path, 'a') as result:
result.write(f.read())
```
需要注意的是,如果要执行这段代码,需要将其中的路径修改为实际的路径。