Advertisement
Guest User

Untitled

a guest
Oct 3rd, 2015
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.81 KB | None | 0 0
  1. """Will add doc str soon!"""
  2. import os
  3. from sys import exit
  4. import json
  5. from tkinter import filedialog, Tk
  6.  
  7. __author__ = 'Cow_Fu'
  8.  
  9.  
  10. # noinspection PyBroadException
  11. class FileMethods:
  12.     """
  13.    This class is to use for the various file
  14.    """
  15.  
  16.     # make a first time use thingy
  17.     # add better exception handling to each method
  18.  
  19.     @staticmethod
  20.     def getDir():
  21.         root = Tk()
  22.         root.withdraw()
  23.  
  24.         return filedialog.askdirectory()
  25.  
  26.     @staticmethod
  27.     def testValidPath(path):
  28.         """
  29.        Checks to see if the file exists
  30.        :type path: str
  31.        :rtype: bool
  32.        """
  33.  
  34.         if path == "":  # change this to something better
  35.  
  36.             return os.path.exists(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json")
  37.  
  38.         else:
  39.             return os.path.exists(path)
  40.  
  41.     @staticmethod
  42.     def createFile():
  43.         """
  44.        This function creates a file
  45.        :rtype: None
  46.        """
  47.  
  48.         if not FileMethods.testValidPath(os.path.expanduser("~") + "\AppData\Roaming\FileSorter"):
  49.             FileMethods.createPath()
  50.  
  51.             try:
  52.                 f = open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "w+")
  53.             except Exception as e:
  54.                 print("A floppy error has occurred!")
  55.                 print(e.args)
  56.                 print(e.__cause__)
  57.  
  58.     @staticmethod
  59.     def createPath():
  60.  
  61.         try:
  62.             os.mkdir(os.path.expanduser("~") + "\AppData\Roaming\File Sorter")
  63.         except Exception as e:
  64.             print("An error has occurred!")
  65.             print(e.args)
  66.             print(e.__cause__)
  67.  
  68.     @staticmethod
  69.     def readData():
  70.         """
  71.        This function reads data from file and returns the value
  72.        :rtype: dict
  73.        """
  74.         try:
  75.             with open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "r") as f:
  76.                 return json.load(f)
  77.         except Exception as e:
  78.             if not e.args.__str__().find('Expecting value: line 1 column 1 (char 0)'):
  79.                 print("An error has occurred while reading the data!")
  80.                 print(e.args)
  81.                 print(e.__cause__)
  82.  
  83.     @staticmethod
  84.     def writeAllData(data):
  85.         """
  86.        This function writes the data to a file and returns true if successful, or false otherwise
  87.        :param data: dict
  88.        :rtype: bool
  89.        """
  90.         try:
  91.             with open(os.path.expanduser("~") + "\AppData\Roaming\File Sorter\File_Sorter_Data.json", "w+") as f:
  92.                 json.dump(data, f)
  93.  
  94.             return True
  95.  
  96.         except Exception as e:
  97.             print("An error has occurred while writing the data!")
  98.             print(e.args)
  99.             print(e.__cause__)
  100.  
  101.             return False
  102.  
  103.  
  104. class FileSorterMethods:
  105.     """
  106.    This class contains all the methods for sorting the files
  107.    """
  108.  
  109.     @staticmethod
  110.     def getKey():
  111.         """
  112.        Gets Key from user
  113.        :rtype: str
  114.        """
  115.  
  116.         key = input()
  117.  
  118.         return key
  119.  
  120.     @staticmethod
  121.     def getValue():
  122.         """
  123.        Gets Value from user
  124.        :rtype: str
  125.         """
  126.         value = FileMethods.getDir()
  127.  
  128.         return value
  129.  
  130.     @staticmethod
  131.     def addItem():
  132.         """
  133.        Returns new item to search for
  134.        :rtype: dict
  135.        """
  136.         while True:
  137.             data = {}
  138.  
  139.             print("Please enter the key we'll search for:")
  140.             key = FileSorterMethods.getKey()
  141.  
  142.             print("Please select where it will move the file:")
  143.             value = FileSorterMethods.getValue()
  144.  
  145.             # TODO add something so this can be changed without starting again
  146.             if os.path.exists(value):
  147.                 answer = input('Move files with names containing "{0}" to "{1}"\n(y/n)?: '.format(key, value))
  148.  
  149.                 if answer.lower() == "y":
  150.                     data[key] = value
  151.  
  152.                     return data
  153.                 else:
  154.                     # TODO make this smarter
  155.                     continue
  156.             else:
  157.                 print("Sorry, but that's not a valid path!")
  158.                 if input("Try again? (y/n): ").lower() is not "y":
  159.                     break
  160.  
  161.     @staticmethod
  162.     def getKeyList(data):
  163.         """
  164.        :type data: dict
  165.        :rtype: list
  166.        """
  167.  
  168.         key = data.keys()
  169.         key = key.__str__()
  170.         key = str(key[11:len(key) - 3])
  171.  
  172.         listOfKeys = key.split("', ")
  173.         newListOfKeys = []
  174.  
  175.         for i in listOfKeys:
  176.             newStr = i[1::]
  177.  
  178.             newListOfKeys.append(newStr)
  179.  
  180.         return newListOfKeys
  181.  
  182.     @staticmethod
  183.     def getValueList(data):
  184.         """
  185.        :type data: dict
  186.        :rtype: list
  187.        """
  188.  
  189.         value = data.values()
  190.         value = value.__str__()
  191.         value = str(value[13:len(value) - 3])
  192.  
  193.         listOfValues = value.split("', ")
  194.         newListOfValues = []
  195.  
  196.         for i in listOfValues:
  197.             newStr = i[1::]
  198.             newListOfValues.append(newStr)
  199.  
  200.         return newListOfValues
  201.  
  202.     @staticmethod
  203.     def welcome():
  204.         print("""
  205. Hello! Welcome to my file sorter thingy!
  206.  
  207. Before we begin, we need to add your first keyword.
  208. This keyword is what we'll look for in the file's name.
  209. For example, lets say we want to move any file in our documents folder with "cheese" in its name to our desktop.
  210. To do this, we would place this file in our documents folder and add a new item to the list to search for.
  211. The keyword would be "cheese", and find the desktop with the file path selector.
  212. In this case, it would look something like "C:\\Users\*replace with your username*\Desktop"
  213. Then, simply run the file!
  214.  
  215. Alright, so lets go ahead and make our first entry!
  216. """)
  217.  
  218.         newData.update(FileSorterMethods.addItem())
  219.  
  220.         keys.__iadd__(FileSorterMethods.getKeyList(newData))
  221.         values.__iadd__(FileSorterMethods.getValueList(newData))
  222.  
  223.         data.update(newData)
  224.  
  225.         if FileMethods.writeAllData(data):
  226.             print("Added Successfully.")
  227.  
  228.         newData.clear()
  229.  
  230.         if FileMethods.writeAllData(data):
  231.             print("Added Successfully.")
  232.  
  233.         print("\nThat's all there is too it!\nNow, lets get started!")
  234.  
  235.  
  236. def updateNewData():
  237.     newData.update(FileSorterMethods.addItem())
  238.  
  239.     keys.__iadd__(FileSorterMethods.getKeyList(newData))
  240.     values.__iadd__(FileSorterMethods.getValueList(newData))
  241.  
  242.     data.update(newData)
  243.  
  244.  
  245. # dictionaries
  246. data = {}
  247. newData = {}
  248.  
  249. # lists
  250. keys = []
  251. values = []
  252.  
  253.  
  254. # this gets the users path:
  255. # os.path.expanduser("~")
  256.  
  257.  
  258. # TODO Add log of where it moves the files to
  259. # TODO add thing to start a person off, and get them to add something to keywords
  260. # use file open mode "a" to append to a file
  261. if not FileMethods.testValidPath(""):
  262.     FileMethods.createFile()
  263.     FileSorterMethods.welcome()
  264.  
  265. try:
  266.     data = FileMethods.readData()
  267.     if not data:
  268.         data = {}
  269.         print("Uh oh, looks like your list of items is empty!\nPlease add at least one to continue.\n")
  270.  
  271.         updateNewData()
  272.  
  273. except Exception as e:
  274.  
  275.     print(e.args)
  276.     exit(0)
  277.  
  278. while True:
  279.     if not data:
  280.         data = {}
  281.         print("Uh oh, looks like your list of items is empty!\nPlease add at least one to continue.\n")
  282.         data = FileSorterMethods.addItem()
  283.  
  284.     llama = input("\nEnter the number for the corresponding operation, or enter to start sorting:"
  285.                   "\n1. Add new entry\n2. Delete entry\n3. Print list\n4. Exit\n")
  286.  
  287.     if llama == "":
  288.         # sorting
  289.         cwd = os.getcwd()
  290.  
  291.         for file in next(os.walk(cwd))[2]:
  292.             lowerFile = file.lower()
  293.             for key in keys:
  294.                 if lowerFile.__contains__(key.lower()):
  295.                     path = data.get(key)
  296.                     print('File: "{0}" from "{1}" -> "{2}"'.format(file, cwd, path))
  297.                     try:
  298.                         os.rename(cwd + "\\" + file, path + "\\" + file)
  299.                     except Exception as e:
  300.                         print("An error has occurred!")
  301.                         print(e.args)
  302.                         print(e.__cause__)
  303.                         exit(-1)
  304.  
  305.     elif llama == '1':
  306.         # add new entry
  307.         # can't run this more than once
  308.  
  309.         updateNewData()
  310.  
  311.         if FileMethods.writeAllData(data):
  312.             print("Added Successfully.")
  313.  
  314.         newData.clear()
  315.  
  316.     elif llama == '2':
  317.         # del entry
  318.         i = -1
  319.  
  320.         print("")
  321.         for key in keys:
  322.             i += 1
  323.             print("{0}. {1}".format(i + 1, key))
  324.  
  325.         keyToRemove = input("Please enter the number by the keyword you want to delete: ")
  326.  
  327.         otherThingy = 1
  328.         print("")
  329.  
  330.         for key in keys:
  331.  
  332.             if str(otherThingy) == keyToRemove:
  333.                 answer = input('Remove key "{0}" from list (y/n)?'.format(key))
  334.                 if answer == "y":
  335.                     del data[key]
  336.                     del keys[otherThingy - 1]
  337.                     del values[otherThingy - 1]
  338.  
  339.                     print('Key "{0}" has been removed.'.format(key))
  340.                     if FileMethods.writeAllData(data):
  341.                         print("Removed Successfully.")
  342.                     break
  343.                 else:
  344.                     print("Canceled")
  345.                     break
  346.             otherThingy += 1
  347.  
  348.  
  349.     elif llama == '3':
  350.         # print list
  351.  
  352.         # noinspection PyCallByClass
  353.         print("")
  354.         for i in range(len(keys)):
  355.             # print('The keyword "{0}" will move the file to "{1}"'.format(keys[i], values[i]))
  356.             print('"{0}" -> "{1}"'.format(keys[i], str(values[i]).replace("\\\\", "\\")))
  357.  
  358.     else:
  359.         print("Exiting.")
  360.         exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement