使用Python将特定文件移动到特定文件夹

2024-03-29 11:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建和移动文件,从一个文件夹到另一个这样的方式,有120个文件将在新创建的文件夹内创建一个新的文件夹。你知道吗

这些文件将具有特定的命名结构:X.0.JPEGX.1.JEPGX.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

Tags: 文件pathimage文件夹newifosfolder
1条回答
网友
1楼 · 发布于 2024-03-29 11:28:38

这种“随机性”的原因是由于os.listdir(folder)的工作方式—它以随机顺序返回文件名。From documentation

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

因此,您需要做的是对os.listdir返回的结果进行排序。你知道吗

import os, os.path, shutil
folder = './path' 

lis_dir = [f for f in os.listdir(folder) if ('.' in f and f.split('.')[1].isnumeric())]
images = sorted(lis_dir, key=lambda x: int(x.split('.')[1]))

folderLimit = 120
folderName = images[0].split('.')[0]
newDir = os.path.join(folder, folderName)
folderCount = 0

if not os.path.exists(newDir):
    os.makedirs(newDir)#folder created

for imageCount, image in enumerate(images):
    if (imageCount % folderLimit) == 0:
        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)

相关问题 更多 >