【问题标题】:iterate over a file in a growing folder in python迭代python中不断增长的文件夹中的文件
【发布时间】:2015-11-02 04:28:10
【问题描述】:

我想遍历python文件夹中的所有文件。

此外,假设文件夹正在增长,即文件被异步添加到其中。每当我在迭代时,我都在做一些操作。

因此假设该操作所花费的时间超过了下载速度,这意味着我不会在下载结束之前完成迭代。

如果有任何方法可以做到这一点,请提出建议。你总是可以重新开始,所以请不要建议这种方法。

目前我正在做这样的事情:

onlyfiles = [ f for f in listdir(".") if isfile(join(".",f)) ]

for s in onlyfiles:
    #dosomething

【问题讨论】:

  • 也许保留一组您访问过的所有文件?发布一些代码,显示您尝试过的一些解决方案。
  • 我已经编辑并添加了我现在用于遍历文件夹的代码。

标签: python file python-2.7 directory


【解决方案1】:

我会使用 python sets 来建立一个你已经处理过的文件列表,然后在目录中循环几次,直到你看到所有当前批次的文件感到满意为止。

类似:

 #!/usr/bin/env python

 import os
 import time

 processed = set()
 tripsWithNoChange = 0
 timeToLetWriterCatchUp = 2
 maxNumberOfTrips = 10

 while tripsWithNoChange < maxNumberOfTrips:
     for root,dirs,files in os.walk('.'):
         candidates = set(files)

         # remove the files already visited from consideration
         candidates.difference_update(processed)

         if len(candidates) == 0:
             tripsWithNoChange += 1
             continue

         for f in candidates:
             # process file
             pass

         processed.update(candidates)

         time.sleep(timeToLetWriterCatchUp)

在这种方法中有几个 magic 数字,您需要调整它们,直到您确信所有文件都已处理完毕,特别是:

  • tripsWithNoChange
  • timeToLetWriterCatchUp
  • maxNumberOfTrips

也许这会给你一些想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多