os.walk() applied in an order program

Viewed 58

I would like to make use of walk.os in my specific case where I order some images because of it's hour. The images are in the folder "D:/TR/Eumetsat_IR_photos/Prueba" and my idea would be to get all the images from different folders contained in "D:/TR/Eumetsat_IR_photos" to order them into two specific folders called Daytime and Nighttime. I don't know how to adapt the program to use this os.walk()

It's not important but the hour of the images appears in all the images name in position 37 and 39 (so you can undestand it properly).

Thanks

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)
1 Answers

With a little modification of your code something like this will do it:

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)
Related