Sina Sh Sina Sh - 2 months ago 8
Python Question

Correct path, based on date-style (e.g /2016-01-10) in python script

I wrote an script such as below that checks the content of the newly created/modified folders in

PARENT_DIR
(in this example within last 45 minutes) and makes a copy of those folders on specified path at
MOVE_DIR
.

import os
from shutil import copytree
from time import time

def mins_since_mod(fname):
"""Return time from last modification in minutes"""
return (time() - os.path.getmtime(fname)) / 60

PARENT_DIR = '/home/B/A/(..?)'
MOVE_DIR = '/home/A/Updated_Folders'

# Loop over files in PARENT_DIR
for fname in os.listdir(PARENT_DIR):
# If the file is a directory and was modified in last 45 minutes
if os.path.isdir(fname) and mins_since_mod(fname) < 45:
copytree(fname, MOVE_DIR) # move it to a new location


There's another script (which is out of our interest, but) creates and names new folders based on the date, from time to time (for example there are
/B/A/2015-12-10
,
/B/A/2015-12-25
,
/B/A/2016-01-11
,
/B/A/2016-01-12
etc.)

I'd like to choose only the folder that is created today (kind of dynamic naming for the path at
PARENT_DIR
e.g:
/2016-01-12
for today) and just make a copy of it at the destination. I don't want to check and enter the path every time manually and prefer it to be done automatically everyday. by just executing the script.

How am I supposed to address the
PARENT_DIR = '/home/B/A/(..?)'
in order to achieve this goal?

p.s: I was trying to use PARENT_DIR = '/home/B/A/$(date +%Y-%m-%d)' but it didn't work out...

any kind of help is appreciated.

Answer

I solved my problem with these changes:

import os
import datetime
from shutil import copytree
from shutil import move
from time import time


def mins_since_mod(fname):
"""Return time from last modification in minutes"""
return (time() - os.path.getmtime(fname)) / 60
today = datetime.date.today()
PARENT_DIR = '/home/B/A/'+str(today)
MOVE_DIR = '/home/B/A/BackMeUp'

# Loop over files in PARENT_DIR
for fname in os.listdir(PARENT_DIR):
# If the file is a directory and was modified in last 15 minutes
if os.path.isdir(fname) and mins_since_mod(fname) < 60:
   copytree(fname, MOVE_DIR) # move it to a new location
Comments