每当在 Python 的目录中添加新的 folder/file 时自动执行脚本

Automate the Script whenever a new folder/file is added in directory in Python

我在一个目录下有多个文件夹,每个文件夹都有多个文件。我有一个代码检查每个文件夹中的特定文件,如果存在特定文件,则进行一些数据预处理和分析。 下面给出了它的一个片段。

import pandas as pd
import json
import os

rootdir = os.path.abspath(os.getcwd())

df_list = []

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.startswith("StudyParticipants") and file.endswith(".csv"):
            temp = pd.read_csv(os.path.join(subdir, file))
                           .....
                           ..... 
                          'some analysis'

Merged_df.to_excel(path + '\Processed Data Files\Study_Participants_Merged.xlsx')

现在,我想自动化这个过程。 我希望在添加新文件夹时执行此脚本。这是我第一次探索自动化过程,我坚持了很长一段时间没有取得重大进展。

我正在使用 windows 系统和 Jupyter notebook 创建这些数据帧并执行分析。

非常感谢任何帮助。 谢谢

看看看门狗。

http://thepythoncorner.com/dev/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/

您也可以自己编写一个非常简单的看门狗服务。

  1. 列出你要观察的目录下的所有文件
  2. 等待您定义的时间跨度,比如每隔几秒
  3. 再次创建文件系统列表
  4. 比较两个列表,求其差
  5. 此差异的结果列表是您的文件系统更改

最诚挚的问候

我写了一个脚本,您只需 运行 一次就可以使用。 请注意:

1.) 此解决方案不考虑创建了哪个文件夹。如果需要此信息,我可以重写答案。

2.) 此解决方案假定不会从主文件夹中删除文件夹。如果不是这种情况,我也可以重写答案。

import time
import os


def DoSomething():
    pass


if __name__ == '__main__':
    # go to folder of interest
    os.chdir('/home/somefolders/.../A1')
    # get current number of folders inside it
    N = len(os.listdir())
    while True:
        time.sleep(5)  # sleep for 5 secs
        if N != len(os.listdir()):
            print('New folder added! Doing something useful...')
            DoSomething()
            N = len(os.listdir())  # update N