os.walk已应用于订单程序

问题描述

我想在我的特殊情况下利用walk.os,因为我要订购一些图像,所以要花一些时间。这些图像位于文件夹“ D:/ TR / Eumetsat_IR_photos / Prueba”中,我的想法是从“ D:/ TR / Eumetsat_IR_photos”中包含的不同文件夹中获取所有图像,以将它们排序为两个特定的文件夹,称为白天和夜间。我不知道如何修改程序以使用此os.walk()

这并不重要,但是图像的小时数会出现在所有图像名称中的位置37和39(以便您正确地理解它)。

谢谢

from os import listdir,path,mkdir
import shutil


directorio_origen = "D:/TR/Eumetsat_IR_photos/Prueba"
directorio_destino_dia = "D:/TR/IR_Photos/Daytime"
directorio_destino_noche = "D:/TR/IR_Photos/Nighttime"

def get_hour(file_name):
    return file_name[37:39]

for fn in list0:
    hora = int(get_hour(fn))
    file_directorio= directorio_origen+"/"+fn
    if 6 < hora < 19: 
        new_directorio= directorio_destino_dia
    else:
        new_directorio= directorio_destino_noche
        
    try:
        if not path.exists(new_directorio):
            mkdir(new_directorio)
        shutil.copy(file_directorio,new_directorio)
    except OSError:
        print("el archivo %s no se ha ordenado" % fn)

解决方法

只需稍微修改一下代码,即可完成以下操作:

import shutil
import os

directorio_origen = "D:/TR/Eumetsat_IR_photos/Prueba"
directorio_destino_dia = "D:/TR/IR_Photos/Daytime"
directorio_destino_noche = "D:/TR/IR_Photos/Nighttime"

def get_hour(file_name):
    return file_name[37:39]

for root,dirs,files in os.walk(directorio_origen,topdown=False):
    for fn in files:
        path_to_file = os.path.join(root,fn)
        hora = int(get_hour(fn))
        new_directorio = ''
        if 6 < hora < 19: 
            new_directorio= directorio_destino_dia
        else:
            new_directorio= directorio_destino_noche
        try:
            if not os.path.exists(new_directorio):
                os.mkdir(new_directorio)
            shutil.copy(path_to_file,new_directorio)
        except OSError:
            print("el archivo %s no se ha ordenado" % fn)