如果列表对象包含从列表中删除的内容

时间:2011-07-21 08:53:40

标签: python list pop

我有一个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]

我的想法是,在填充添加后,它会检查它是否具有状态,并从数组中弹出它。找不到办法做到这一点:/

提前致谢, Tanel-尼尔斯

4 个答案:

答案 0 :(得分:2)

如果我理解你的问题:

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以避免无用的检查。

答案 1 :(得分:1)

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

但我建议不要使用长行语句,因为它们使代码几乎无法读取

答案 2 :(得分:1)

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

答案 3 :(得分:0)

您可以使用set逻辑,因为这里的顺序无关紧要:

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)