简体   繁体   中英

In python, how do I copy files into a directory and stop once that directory reaches a certain size

I am still very new to Python, but I am trying to create a program which will, among other things, copy the contents of a directory into a set of directories that will fit onto a disc (I have it set up the following variables to be the size capacities I want, and set up an input statement to say which one applies):

BluRayCap = 25018184499
DVDCap = 4617089843
CDCap = 681574400

So basically I want to copy the contents of a beginning directory into another directory, and as needed, create another directory in order for the contents to fit into discs.

I kind of hit a roadblock here. Thanks!

You can use os.path.getsize to get the size of a file, and you can use os.walk to walk a directory tree, so something like the following (I'll let you implement CreateOutputDirectory and 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)

Also, you may find the Python Search extension for Chrome helpful for looking up this documentation.

Michael Aaron Safyan's answer is good.

Besides, you can use shutil module to CreateOutputDirectory and CopyFileToDirectory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM