Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Will add doc str soon!"""
- import os
- from sys import exit
- import json
- from tkinter import filedialog, Tk
- __author__ = 'Cow_Fu'
- # noinspection PyBroadException
- class FileMethods:
- """
- This class is to use for the various file
- """
- # make a first time use thingy
- # add better exception handling to each method
- @staticmethod
- def getDir():
- root = Tk()
- root.withdraw()
- return filedialog.askdirectory()
- @staticmethod
- def testValidPath(path):
- """
- Checks to see if the file exists
- :type path: str
- :rtype: bool
- """
- if path == "": # change this to something better
- return os.path.exists(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json")
- else:
- return os.path.exists(path)
- @staticmethod
- def createFile():
- """
- This function creates a file
- :rtype: None
- """
- if not FileMethods.testValidPath(os.path.expanduser("~") + "\AppData\Roaming\FileSorter"):
- FileMethods.createPath()
- try:
- f = open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "w+")
- except Exception as e:
- print("A floppy error has occurred!")
- print(e.args)
- print(e.__cause__)
- @staticmethod
- def createPath():
- try:
- os.mkdir(os.path.expanduser("~") + "\AppData\Roaming\File Sorter")
- except Exception as e:
- print("An error has occurred!")
- print(e.args)
- print(e.__cause__)
- @staticmethod
- def readData():
- """
- This function reads data from file and returns the value
- :rtype: dict
- """
- try:
- with open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "r") as f:
- return json.load(f)
- except Exception as e:
- if not e.args.__str__().find('Expecting value: line 1 column 1 (char 0)'):
- print("An error has occurred while reading the data!")
- print(e.args)
- print(e.__cause__)
- @staticmethod
- def writeAllData(data):
- """
- This function writes the data to a file and returns true if successful, or false otherwise
- :param data: dict
- :rtype: bool
- """
- try:
- with open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "w+") as f:
- json.dump(data, f)
- return True
- except Exception as e:
- print("An error has occurred while writing the data!")
- print(e.args)
- print(e.__cause__)
- return False
- class FileSorterMethods:
- """
- This class contains all the methods for sorting the files
- """
- @staticmethod
- def getKey():
- """
- Gets Key from user
- :rtype: str
- """
- key = input()
- return key
- @staticmethod
- def getValue():
- """
- Gets Value from user
- :rtype: str
- """
- value = FileMethods.getDir()
- return value
- @staticmethod
- def addItem():
- """
- Returns new item to search for
- :rtype: dict
- """
- while True:
- data = {}
- print("Please enter the key we'll search for:")
- key = FileSorterMethods.getKey()
- print("Please select where it will move the file:")
- value = FileSorterMethods.getValue()
- # TODO add something so this can be changed without starting again
- if os.path.exists(value):
- answer = input('Move files with names containing "{0}" to "{1}"\n(y/n)?: '.format(key, value))
- if answer.lower() == "y":
- data[key] = value
- return data
- else:
- # TODO make this smarter
- continue
- else:
- print("Sorry, but that's not a valid path!")
- if input("Try again? (y/n): ").lower() is not "y":
- break
- @staticmethod
- def getKeyList(data):
- """
- :type data: dict
- :rtype: list
- """
- key = data.keys()
- key = key.__str__()
- key = str(key[11:len(key) - 3])
- listOfKeys = key.split("', ")
- newListOfKeys = []
- for i in listOfKeys:
- newStr = i[1::]
- newListOfKeys.append(newStr)
- return newListOfKeys
- @staticmethod
- def getValueList(data):
- """
- :type data: dict
- :rtype: list
- """
- value = data.values()
- value = value.__str__()
- value = str(value[13:len(value) - 3])
- listOfValues = value.split("', ")
- newListOfValues = []
- for i in listOfValues:
- newStr = i[1::]
- newListOfValues.append(newStr)
- return newListOfValues
- @staticmethod
- def welcome():
- print("""
- Hello! Welcome to my file sorter thingy!
- Before we begin, we need to add your first keyword.
- This keyword is what we'll look for in the file's name.
- For example, lets say we want to move any file in our documents folder with "cheese" in its name to our desktop.
- To do this, we would place this file in our documents folder and add a new item to the list to search for.
- The keyword would be "cheese", and find the desktop with the file path selector.
- In this case, it would look something like "C:\\Users\*replace with your username*\Desktop"
- Then, simply run the file!
- Alright, so lets go ahead and make our first entry!
- """)
- newData.update(FileSorterMethods.addItem())
- keys.__iadd__(FileSorterMethods.getKeyList(newData))
- values.__iadd__(FileSorterMethods.getValueList(newData))
- data.update(newData)
- if FileMethods.writeAllData(data):
- print("Added Successfully.")
- newData.clear()
- if FileMethods.writeAllData(data):
- print("Added Successfully.")
- print("\nThat's all there is too it!\nNow, lets get started!")
- def updateNewData():
- newData.update(FileSorterMethods.addItem())
- keys.__iadd__(FileSorterMethods.getKeyList(newData))
- values.__iadd__(FileSorterMethods.getValueList(newData))
- data.update(newData)
- # dictionaries
- data = {}
- newData = {}
- # lists
- keys = []
- values = []
- # this gets the users path:
- # os.path.expanduser("~")
- # TODO Add log of where it moves the files to
- # TODO add thing to start a person off, and get them to add something to keywords
- # use file open mode "a" to append to a file
- if not FileMethods.testValidPath(""):
- FileMethods.createFile()
- FileSorterMethods.welcome()
- try:
- data = FileMethods.readData()
- if not data:
- data = {}
- print("Uh oh, looks like your list of items is empty!\nPlease add at least one to continue.\n")
- updateNewData()
- except Exception as e:
- print(e.args)
- exit(0)
- while True:
- if not data:
- data = {}
- print("Uh oh, looks like your list of items is empty!\nPlease add at least one to continue.\n")
- data = FileSorterMethods.addItem()
- llama = input("\nEnter the number for the corresponding operation, or enter to start sorting:"
- "\n1. Add new entry\n2. Delete entry\n3. Print list\n4. Exit\n")
- if llama == "":
- # sorting
- cwd = os.getcwd()
- for file in next(os.walk(cwd))[2]:
- lowerFile = file.lower()
- for key in keys:
- if lowerFile.__contains__(key.lower()):
- path = data.get(key)
- print('File: "{0}" from "{1}" -> "{2}"'.format(file, cwd, path))
- try:
- os.rename(cwd + "\\" + file, path + "\\" + file)
- except Exception as e:
- print("An error has occurred!")
- print(e.args)
- print(e.__cause__)
- exit(-1)
- elif llama == '1':
- # add new entry
- # can't run this more than once
- updateNewData()
- if FileMethods.writeAllData(data):
- print("Added Successfully.")
- newData.clear()
- elif llama == '2':
- # del entry
- i = -1
- print("")
- for key in keys:
- i += 1
- print("{0}. {1}".format(i + 1, key))
- keyToRemove = input("Please enter the number by the keyword you want to delete: ")
- otherThingy = 1
- print("")
- for key in keys:
- if str(otherThingy) == keyToRemove:
- answer = input('Remove key "{0}" from list (y/n)?'.format(key))
- if answer == "y":
- del data[key]
- del keys[otherThingy - 1]
- del values[otherThingy - 1]
- print('Key "{0}" has been removed.'.format(key))
- if FileMethods.writeAllData(data):
- print("Removed Successfully.")
- break
- else:
- print("Canceled")
- break
- otherThingy += 1
- elif llama == '3':
- # print list
- # noinspection PyCallByClass
- print("")
- for i in range(len(keys)):
- # print('The keyword "{0}" will move the file to "{1}"'.format(keys[i], values[i]))
- print('"{0}" -> "{1}"'.format(keys[i], str(values[i]).replace("\\\\", "\\")))
- else:
- print("Exiting.")
- exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement