Я пытаюсь прокрутить каталог, проверить размер каждого файла и добавить файлы в список, пока они не достигнут определенный размер (2040 MB). В этот момент я хочу поместить список в zip-архив, а затем продолжить цикл через следующий набор файлов в каталоге и продолжать делать то же самое. Другим ограничением является то, что файлы с тем же именем, но разные расширения должны быть добавлены вместе в zip и не могут быть разделены. Я надеюсь, что в этом есть смысл.Python: Постоянно проверяйте размер добавляемых файлов в список, останавливайтесь в размере, списке zip, продолжайте
Проблема, с которой я сталкиваюсь, заключается в том, что мой код в основном игнорирует ограничение размера, которое я добавил, и просто застегивает все файлы в каталоге в любом случае.
Я подозреваю, что есть какая-то логическая проблема, но я не вижу ее. Любая помощь будет оценена по достоинству. Вот мой код:
import os,os.path, zipfile
from time import *
#### Function to create zip file ####
# Add the files from the list to the zip archive
def zipFunction(zipList):
# Specify zip archive output location and file name
zipName = "D:\Documents\ziptest1.zip"
# Create the zip file object
zipA = zipfile.ZipFile(zipName, "w", allowZip64=True)
# Go through the list and add files to the zip archive
for w in zipList:
# Create the arcname parameter for the .write method. Otherwise the zip file
# mirrors the directory structure within the zip archive (annoying).
arcname = w[len(root)+1:]
# Write the files to a zip
zipA.write(w, arcname, zipfile.ZIP_DEFLATED)
# Close the zip process
zipA.close()
return
#################################################
#################################################
sTime = clock()
# Set the size counter
totalSize = 0
# Create an empty list for adding files to count MB and make zip file
zipList = []
tifList = []
xmlList = []
# Specify the directory to look at
searchDirectory = "Y:\test"
# Create a counter to check number of files
count = 0
# Set the root, directory, and file name
for root,direc,f in os.walk(searchDirectory):
#Go through the files in directory
for name in f:
# Set the os.path file root and name
full = os.path.join(root,name)
# Split the file name from the file extension
n, ext = os.path.splitext(name)
# Get size of each file in directory, size is obtained in BYTES
fileSize = os.path.getsize(full)
# Add up the total sizes for all the files in the directory
totalSize += fileSize
# Convert from bytes to megabytes
# 1 kilobyte = 1,024 bytes
# 1 megabyte = 1,048,576 bytes
# 1 gigabyte = 1,073,741,824 bytes
megabytes = float(totalSize)/float(1048576)
if ext == ".tif": # should be everything that is not equal to XML (could be TIF, PDF, etc.) need to fix this later
tifList.append(n)#, fileSize/1048576])
tifSorted = sorted(tifList)
elif ext == ".xml":
xmlList.append(n)#, fileSize/1048576])
xmlSorted = sorted(xmlList)
if full.endswith(".xml") or full.endswith(".tif"):
zipList.append(full)
count +=1
if megabytes == 2040 and len(tifList) == len(xmlList):
zipFunction(zipList)
else:
continue
eTime = clock()
elapsedTime = eTime - sTime
print "Run time is %s seconds"%(elapsedTime)
Единственное, что я могу думать о том, что никогда не тот случай, когда моя переменная megabytes==2040
точно. Я не могу понять, как сделать код останавливаться в этой точке в противном случае; Интересно, работает ли диапазон? Я также попытался:
if megabytes < 2040:
zipList.append(full)
continue
elif megabytes == 2040:
zipFunction(zipList)