根据 Python 的大小(以 MB 为单位)拆分文件集

Split set of files based on size in MB with Python

有什么方法可以在 Python 中添加一个函数,它可以遍历包含文件列表的文件夹,并根据文件的总大小将列表分成 "partitions"(这将成为文件夹)每个 partition/folder 中的文件以兆字节为单位?我不确定如何开始或首先做什么。

假设您想要一个起点,而不是一蹴而就的解决方案:

  • 使用 os.walk to scan a whole directory tree. If you only need to scan one folder, not a whole tree, you can optimize a bit without sacrificing simplicity (particularly on Windows) on Python 3.5 with the new os.scandir 功能,可以免费为您提供 Windows 上的 stat 信息(并使其在 *NIX 系统上可作为延迟缓存值访问)。在 Python 的早期版本中,PyPI 上的第三方 scandir 模块提供了相同的接口。
  • 如果不使用 os.scandir,您将使用 os.stat 获取文件大小
  • 使用 collections.defaultdict(set) 将以 MB 为单位的文件大小映射到 set 舍入到该大小的文件(或者直接处理文件而不是完全存储在容器中).或者,使用 sorted key-ed 按大小排序并使用 itertools.groupby(以您喜欢的任何 MB 粒度)对结果文件进行分组。