【问题标题】:In python, how do I copy files into a directory and stop once that directory reaches a certain size在python中,如何将文件复制到目录中并在该目录达到一定大小时停止
【发布时间】:2011-08-05 03:50:09
【问题描述】:

我对 Python 还是很陌生,但我正在尝试创建一个程序,它可以将目录的内容复制到一组可以放入光盘的目录中(我已经设置了以下变量是我想要的大小容量,并设置一个输入语句来说明哪个适用):

BluRayCap = 25018184499
DVDCap = 4617089843
CDCap = 681574400

所以基本上我想将一个开始目录的内容复制到另一个目录中,并根据需要创建另一个目录以使内容适合光盘。

我在这里遇到了障碍。谢谢!

【问题讨论】:

    标签: python copy directory


    【解决方案1】:

    您可以使用os.path.getsize 来获取文件的大小,并且您可以使用os.walk 来遍历目录树,如下所示(我将让您实现 CreateOutputDirectory 和 CopyFileToDirectory):

    current_destination = CreateOutputDirectory()
    for root, folders, files in os.walk(input_directory):
       for file in files:
           file_size = os.path.getsize(file)
           if os.path.getsize(current_destination) + file_size > limit:
              current_destination = CreateOutputDirectory()
           CopyFileToDirectory(root, file, current_destination)
    

    此外,您可能会发现 Chrome 的 Python Search 扩展有助于查找此文档。

    【讨论】:

    • 这听起来像我需要的。我将不得不努力实现这两个功能,但现在我有了更坚实的方向。谢谢!
    【解决方案2】:

    Michael Aaron Safyan 的回答很好。

    此外,您可以使用 shutil 模块来CreateOutputDirectoryCopyFileToDirectory

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2019-11-01
      • 2016-08-04
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多