Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, shutil, shelve, time
- #Backup.py
- #Backs shit up
- def BackUpAll (path, bupath):
- #Gets the name from the original folder and makes a new one
- names = os.path.split(path)
- new_name = names[1]+' '+GetTime()
- new_path = bupath + "\\" + new_name
- print("Copying files from %s to %s"%(path,new_path))
- #shutil.copy(path,new_path)
- def CheckBUPath ():
- """Gets a path from user and checks if it's empty.
- If not, it asks the user if he wants to change it."""
- create_path=True
- while create_path:
- #Creating Backup path
- print("Where would you like to create your backup?")
- path = MakePath()
- os.chdir(path)
- #Checking if something already exists at that path
- if len(os.listdir()) >= 1:
- print("\nSomething already exists there: ")
- resume = Walkpath(path,"Short")
- print("%d folders and %d documents\n"%(resume[0],resume[1]))
- print('Would you like to change your location?')
- answer = YesNo()
- if answer =="YES" or answer =="Y":
- continue
- elif answer =="NO" or answer =="N":
- break
- else:
- print("The path is empty! Proceeding with setup...")
- return path
- def GetTime():
- """Gets the time in a DD/MM/YY-HH/MM/SS format"""
- date = time.strftime("%x")
- hour = time.strftime("%X")
- full_time = date+'-'+hour
- return full_time
- def MakePath ():
- """Gets a valid path from user."""
- while True:
- path = input("Enter path here: ").strip(' ')
- if not os.path.exists(path):
- print("That path does not exist, please enter a valid path.")
- else:
- break
- return path
- def Setup():
- """Walks the user through setting a path location and other settings"""
- print("We will walk you around creating your backup and backup preferences\n")
- #Setting the directory to be backed up
- print("What directory would you like to backup?")
- path = MakePath()
- print("Would you like to se all folders and files at that path? (enter YES|NO)")
- answer = YesNo()
- if answer =="YES" or answer =="Y":
- Walkpath(path)
- elif answer =="NO" or answer =="N":
- print("\n")
- print("Okay, let's proceed.")
- else:
- raise Exception ("Something went wrong with your answer")
- answer="" #AnswerReset
- #Setting the backup directory
- bupath = CheckBUPath()
- print("Would you like to save this destination (%s) as your default backup location ?\
- That way you don't have to type it again."%bupath)
- answer = YesNo()
- if answer =="YES" or answer =="Y":
- WorkShelf('BackUpPath','store', bupath)
- else:
- print("Okay, let's proceed")
- answer = "" #AnswerReset
- #Remembering files to be backed up location
- print("\nIf you're going to be backing the same data up\
- we can save the files location so you don't have to type all the paths again.")
- print("Would you like me to remember the backup file's location?")
- answer = YesNo()
- if answer =="YES" or answer =="Y":
- WorkShelf('Path2BU', 'store', path)
- else:
- print("Okay, let's proceed")
- answer = "" #AnswerReset
- return path, bupath
- def Walkpath (path, version = 'Long'):
- """Walks a path and prints out all the contents with structure.
- Also gives a short version with number of files and subfolders."""
- walk = os.walk(path)
- #Long
- if version == "Long":
- for (CurrentDir, Subdirs, Docs) in walk:
- print('___________\n')
- print('CURRENT FOLDER: ',CurrentDir)
- if len(Subdirs) >= 1:
- print("This folder (%s) contains the following subfolders: "%CurrentDir)
- for subdir in Subdirs:
- print("\t-", subdir)
- else:
- print("No subfolders found")
- if len(Docs) >= 1:
- print("This folder (%s) contains the following documents: "%CurrentDir)
- for doc in Docs:
- print("\t-", doc)
- else:
- print("No documents found")
- print('\n'*4)
- #Short
- elif version == "Short":
- nb_subs, nb_docs = 0,0
- for (CurrentDir, Subdirs, Docs) in walk:
- for subdir in Subdirs:
- nb_subs += 1
- for doc in Docs:
- nb_docs += 1
- resume = [nb_subs, nb_docs]
- return resume
- else:
- raise Exception ('Error in Backup.Walkpath')
- def WorkShelf(key, mode='get', variable=None):
- """Either stores a variable to the shelf or gets one from it.
- Possible modes are 'store' and 'get'"""
- config = shelve.open('Config')
- if mode.strip() == 'get':
- print(config[key])
- return config[key]
- elif mode.strip() == 'store':
- config[key] = variable
- print(key,'holds',variable)
- else:
- print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'")
- config.close()
- def YesNo ():
- """Gets a valid YES/NO answer from user."""
- while True:
- answer = input("> ").upper().strip(' ')
- if answer == "YES" or answer == "Y" or answer == "NO" \
- or answer == "NOPE" or answer == "N":
- break
- else:
- print("You did not enter a valid answer. Possibilities are yes/y|no/nope/n")
- return answer
- # MAIN
- print("Welcome to this backup manager.")
- if False: #First Time
- path, bupath = Setup()
- BackUpAll(path, bupath)
- else:
- os.chdir(r"W:\Users\Damien\Documents\Code\Code Pyth")
- config = shelve.open('Config')
- path = config['Path2BU']
- bupath = config['BackUpPath']
- #path, bupath = WorkShelf('Path2BU'), WorkShelf('BackUpPath')
- print(path, bupath)
- BackUpAll(path, bupath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement