簡體   English   中英

如果列表 object 包含從列表中刪除的內容

[英]If list object contains something remove from list

我有一個 python 腳本,它檢查某個文件夾中的新文件,然后將新文件復制到另一個目錄。 這些文件的格式為 1234.txt 和 1234_status.txt。 它應該只移動 1234.txt 並讓 1234_status.txt 無人看管。

這是我在 python 中的一小段代碼

    while 1:
#retrieves listdir
        after = dict([(f, None) for f in os.listdir (path_to_watch)])
#if after has more files than before, then it adds the new files to an array "added"
        added = [f for f in after if not f in before]

我的想法是,在它填充添加后,它會檢查其中是否有狀態的值並將其從數組中彈出。 雖然找不到這樣做的方法:/

如果我正確理解您的問題:

while 1:
    for f in os.listdir(path_to_watch):
        if 'status' not in f: # or a more appropriate condition
            move_file_to_another_directory(f)
    # wait

或檢查pyinotify如果使用 Linux 以避免無用的檢查。

added = [f for f in after if not f in before and '_status' not in f]

但是,我建議不要使用冗長的單行語句,因為它們使代碼幾乎無法閱讀

files_in_directory = [filename for filename in os.listdir(directory_name)]
files_to_move = filter(lambda filename: '_status' not in filename, files_in_directory)

您可以使用設置邏輯,因為這里的順序無關緊要:

from itertools import filterfalse

def is_status_file(filename):
    return filename.endswith('_status.txt')
# ...
added = set(after) - set(before)
without_status = filterfalse(is_status_file, added)

暫無
暫無

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

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