[英]How to run python code when new file has been added to a folder in desktop?
I am trying to automate a process with VBA and Python.我正在尝试使用 VBA 和 Python 自动化一个过程。 I use a VBA macro to send from my mail, pdf files to a specific folder in my desktop.
我使用 VBA 宏从我的邮件、pdf 文件发送到我桌面上的特定文件夹。 Then I run a code that convert this pdf into csv file.
然后我运行一个将这个 pdf 转换为 csv 文件的代码。 I want to automate the process and make run the python code only in the newest pdf file uploaded.
我想自动化该过程并仅在上传的最新 pdf 文件中运行 python 代码。
I currently use this code for converting the file:我目前使用此代码来转换文件:
import tabula
import pandas as pd
tabula.convert_into(r"pathtofile.pdf", r"pathtofile.csv", pages="all")
After running the code, converted files appear in the folder.运行代码后,转换后的文件出现在文件夹中。 I have seen you can use a library called watchdog to monitor files changes.
我已经看到您可以使用一个名为 watchdog 的库来监视文件更改。 Despite that, i have not found a robust code for this automation,
尽管如此,我还没有找到用于这种自动化的强大代码,
Thanks b4hand and best regards感谢 b4hand 和最好的问候
See if this helps:看看这是否有帮助:
import tabula
import pandas as pd
import os
import time
# The path to the directory you want to monitor
path_to_watch = "C:/Users/YourName/Directory/To/Monitor"
# Any file extension you want to limit by
file_type = ".pdf"
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (10)
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added:
for filename in added:
if filename.endswith(file_type):
tabula.convert_into(filename, filename.replace(file_type, ".csv"), pages="all")
before = after
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.