[英]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.