[英]How to copy all the files in certain Directory and recreate the directory structure dynamically using python
[英]How to list (certain) files in a directory dynamically in Python?
我正在嘗試在目錄中列出(例如)PDF文件(至GUI)。 我知道我可以用不同的方式(如下所示)進行管理,但我也希望列表是最新的和動態的。 例如,如果有人從目錄中刪除PDF文件或將PDF文件添加到目錄中,我希望應用程序立即刪除文件名或將文件名添加到列表中,而無需進行任何刷新。
你知道有什么辦法可以解決嗎?
這是我的一些代碼:
import os
pdffiles = [name for name in os.listdir('somedir')
if name.endswith('.pdf')]
for file in pdffiles:
print(file)
我正在學習中。
您需要通過操作系統通知目錄和/或某些文件已更改。
與平台無關的解決方案是看門狗
將其連接到程序中並非易事,但是看門狗的示例很清楚,這意味着不需要輪詢。
到目前為止,您的代碼看起來不錯。 如果要以編程方式執行此操作(避免pynotify或信號處理),則在應用程序中維護目錄列表的最簡單方法是通過輪詢目錄。
因此,您的代碼可能如下所示:
import os
import time
## run indefinitely
while True:
## get the directory listing
pdffiles = [name for name in os.listdir('somedir')
if name.endswith('.pdf')]
## print the most recent listing
for file in pdffiles:
print(file)
## wait a little bit before getting the next listing
## if you want near instantaneous updates, make the sleep value small.
time.sleep(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.