3

I have a script that copy folder and files from their source to a new destination, the script works as it should using shutil module. But I am hard coding the source for folders.

What I need is to make the script select the desired folder where it has a specific name. as
pdf 11-12-02-2020 so it pdf + date yesterday - current date - current month - current year.

how can I do this ?

code:

import os
import shutil
from os import path
import datetime

src = "I:\\"
src2 = "I:/pdf 11-12-02-2020"

dst = "C:/Users/LT GM/Desktop/pdf 11-12-02-2020/"


def main():
    copy()

def copy():
    if os.path.exists(dst): 
        shutil.rmtree(dst)
        print("the deleted folder is :{0}".format(dst))
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))
    else:
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))

if __name__=="__main__":
    main()
Dev Dj
  • 169
  • 2
  • 14
  • as a side note, I would avoid having spaces in folder/file names in general. some libraries don't handle spaces well(i.e os library).If you need to then using dst=r'string' instead might be better. – koksalb Feb 12 '20 at 09:53

1 Answers1

1

You're looking for the datetime module.

Additionally, you may want to use the os module to resolve the path correctly for you, see this, since the src variable seems unused, it's better to remove it, with all that in mind:

import calendar
import os
import shutil
from datetime import date
from os import path

def yesterday():
    day = int(date.today().strftime("%d"))
    month = int(date.today().strftime("%m"))
    year = int(date.today().strftime("%Y"))
    if day != 1:
        return day - 1
    long_months = [1, 3, 5, 7, 8, 10, 12]
    if month in long_months:
        return 31
    elif month == 2:
        if calendar.isleap(year):
            return 29
        return 28
    else:
        return 30

name = "pdf " + str(yesterday()) + date.today().strftime("-%d-%m-%Y")

src2 = os.path.join("I:/", name)

dst = os.path.join(os.path.expanduser("~"), "Desktop",name)

As a side note, while in this case dst = os.path.join(os.path.expanduser("~"), "Desktop" ,name) works, it's actually not advised to use it, see my answer here

RMPR
  • 3,368
  • 4
  • 19
  • 31
  • what if i have more than 1 folder like **pdf 11-12-02-2020** & **pdf 10-11-02-2020** & **pdf 9-10-02-2020** how can i copy all these folders? – Dev Dj Feb 12 '20 at 11:38