我想创建和移动文件,从一个文件夹到另一个这样的方式,有120个文件将在新创建的文件夹内创建一个新的文件夹。你知道吗
这些文件将具有特定的命名结构:X.0.JPEG
,X.1.JEPG
到X.1200.JPEG
例如://path
创建//path//New_folder
在此之后,文件夹将在此"New_folder"
下创建,120个文件将移动到新文件夹"//path//New_folder//F1//(X.0 to X.119)"
下一个"//path//New_folder//F2//(X.120 to X.239)"
。。。你知道吗
这是我目前的代码,问题是它随机移动文件。你知道吗
import os, os.path, shutil
folder = './path'
images = [
filename
for filename in os.listdir(folder)
if os.path.isfile(os.path.join(folder, filename))
]
global no
no = int(len(images)/120) + 1
img1 = images[0]
global folderName
folderName = img1.split('.')[0]
newDir = os.path.join(folder, folderName)
global folderCount
folderCount = 0
if not os.path.exists(newDir):
os.makedirs(newDir)#folder created
folderLimit = 120
global imageCount
imageCount = 0
for image in images:
if imageCount == folderLimit:
imageCount = 0
if imageCount == 0:
folderCount = folderCount + 1
newfoldername = os.path.join(newDir, folderName + '(' + str(folderCount) + ')' )
os.makedirs(newfoldername)
existingImageFolder = os.path.join(folder, image)
new_image_path = os.path.join(newfoldername, image)
shutil.move(existingImageFolder, new_image_path)
imageCount = imageCount + 1
这种“随机性”的原因是由于
os.listdir(folder)
的工作方式—它以随机顺序返回文件名。From documentation:因此,您需要做的是对
os.listdir
返回的结果进行排序。你知道吗相关问题 更多 >
编程相关推荐