0

I have this situation:

On my HD i have this kind of directory structure:

   root>
   root>dir1>05-13-2018_xxxxxxxx.TXT<br>
   root>dir1>05-14-2018_xxxxxxxx.TXT <-- today file to copy in another dir<br>
   root>dir2>05-13-2018_xxxxxxxx.TXT<br>
   root>dir2>05-14-2018_xxxxxxxx.TXT <-- today file to copy in another dir<br>
   root>dir3>ecc...

i have formatted a python variable who reflect the today date like this data_oggi = str(datetime.datetime.today().strftime('%m-%d-%Y')) i need to scan all subdirs and move the file with match date in filename in another dir...
I'm in empasse,
can anybody help me?
Thank guys for every support.

fferri
  • 18,285
  • 5
  • 46
  • 95

1 Answers1

0

The best way would be using glob module to list all matching files in your source directory and moving them to the destination using shutil.

I hope following will be helpful:

import os

import shutil

import datetime

import glob

BASE = "/root/"

DESTINATION = '/root/test2'

os.path.exists(DESTINATION) or os.makedirs(DESTINATION)

# DIR = 'dir1'
DIR = 'dir1'


def get_file_key():
    """
    Builds file identifier
    """
    return str(datetime.datetime.today().strftime('%m-%d-%Y'))

def move_file(file_path):
    try:
        shutil.move(file_path, DESTINATION)
    except:
        print('file exists....')


if __name__ == '__main__':

    file_for_today = get_file_key()
    files = glob.glob(BASE + '/**/{key}*.txt'.format(key=file_for_today), recursive=True)

    for file in files:
        move_file(file)
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36