簡體   English   中英

在 Python 中查找已更改子目錄中的文件

[英]Find files within a changed subdirectory in Python

我有一個充滿文件名的文本文件。 喜歡:

C:\Folder\Subfolder_01\file_1001.csv
C:\Folder\Subfolder_02\file_3030.xls
...

我想檢查文件是否仍然存在(這很容易)或者子文件夾的名稱是否已更改。 某些子文件夾的名稱通過在其前面添加一些字符串而更改(以 4 位數字開頭,例如C:\\Folder\\Subfolder_02\\file_3030.xls已更改為C:\\Folder\\2019 - Subfolder_02\\file_3030.xls )。

我試圖用pathlib.glob()解決這個問題。 可以“手動”為一個特定文件執行此操作,例如

list(file.parent.parent.glob('* - Subfolder_02\file_3030.xls'))

它返回一個帶有新文件名的列表。 但是我沒有在帶有參數的glob周圍的循環中做到這一點。

這是我到目前為止所得到的,但是由於明顯的原因,我嘗試將 glob 與其他變量(使用 +)連接起來失敗了:

import pathlib

file = pathlib.Path(file_names.txt)
lines=[]

with open(file,'r') as f:
    # reading the txt-file line by line         
    for line in f:
        line = line.replace("\r", "").replace("\n", "")
        lines.append(line)

for file in lines:
    file = pathlib.Path(file)
    # check if file exists ...
    if file.exists():
        print('OK - ' + file.name)
    # ... if not, find new location
    else:
        new_files = list(file.parent.parent.glob('* - ') + file.name)
        print(files_files)  

如果您在原始位置找不到文件,我會將您的頂級目錄設置為路徑,並使用該路徑將目錄下的文件全局化。 在 glob 中使用**將搜索所有文件夾。

# Set top level directory as desired.
parent_dir = Path('.')

# you can use splitlines() to parse the file into a list
with Path('file_names.txt').open() as f:
    files = f.read().splitlines()

for f in files:
    orig = Path(f)

    # Still in location, no need to look further
    if orig.exists():
        print(f"{orig.absolute()} is still in place.")
        continue

    # See if we can find it under parent_dir
    matches = [*parent_dir.glob(f"**/{orig.name}")]

    if len(matches) > 1:
        print("Multiple Matches Found")

    for match in matches:
        print(f"{orig.absolute()} might be in {match.absolute()}")

試試看門狗

例如:

import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

RESOURCES_PATH = "C:\Folder"

class dirs_watcher(FileSystemEventHandler):

    def __init__(self):
        self.observe()
        self.cur_dirs = os.listdir(RESOURCES_PATH)

    def observe(self):
        self.observer = Observer()
        self.my_watch = self.observer.schedule(self, path=RESOURCES_PATH, recursive=True)
        self.observer.start()

    def on_modified(self, event=None):
        # A folder was modified:
        self.new_dirs = os.listdir(RESOURCES_PATH)
        old = set(self.cur_dirs) - set(self.new_dirs)
        new = set(self.new_dirs) - set(self.cur_dirs)
        print("{} changed to {}".format(old, new))

        self.cur_dirs = self.new_dirs # update cur_dirs


on_modified將在子目錄更改時觸發,您可以通過保留子目錄列表來提取更改的文件夾名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM