gpt4 book ai didi

python - 最佳实践 - 观看目录的最佳方式是什么

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:26 26 4
gpt4 key购买 nike

我需要设置一个脚本来监视某个文件夹中是否有某种类型的文件。我编写了这段代码,但我想知道是否有更好的方法?

import os


def listAppleseedFiles(directory_path):
directory_entities = os.listdir(directory_path)
files = []
appleseed_files = []
for entity in directory_entities:
file_path = os.path.join(directory_path, entity)
if os.path.isfile(file_path):
if os.path.splitext(file_path)[1] == '.appleseed':
appleseed_files.append(file_path)

return appleseed_files

while True:
for file in listAppleseedFiles('/dir_name'):

doSomething()

最佳答案

尝试 Watchdog !从他们的例子中:

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path='/dir_name', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

关于python - 最佳实践 - 观看目录的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11882330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com