Clearing the downloads folder using a Python program

Introduction



As a person who is just starting to learn Python, I try to gain new knowledge and skills through direct practice. In my opinion, this approach is better than working out programming guides and multi-volumes. First of all, with projects like the one I’ll talk about, I’m trying to close my needs. In second place is the hope that someone else can come in handy for what I create ( after all existing errors have been fixed )



The idea of ​​this program came at a time when I was trying to find a previously downloaded file among the "garbage" formed in the "Downloads" folder. Images, documents, archives and videos with music: you could understand this confusion and filter files, of course, but you are reluctant because of the large time costs. And I thought that it’s nice to have a program that will parse the “Downloads” folder and distribute the files into the standard folders of the “Images”, “Documents”, “Videos” and “Music” systems, and delete unnecessary files. As a result, the Perfectionist Organizer was born, which I would like to talk about. I must say right away that this is an article from a beginner to beginners, because experienced Python programmers will not find anything useful here ( except the ability to dig into the code and point out a lot of errors ).



General idea



The first thing a program should do is determine in which operating system it is running. This is necessary because on Linux and Windows the Downloads folder is located in different ways (I don’t have the ability to test the program on a Mac, because I didn’t take this OS into account). In the detected download folder, the program goes through all the available files and determines what type they belong to (music, video, documents, etc.). After that, the detected files are moved to the default folders and the program finds out from the user what to do with those files that are not suitable for moving - leave or delete.



Import required libraries and determine the type of system



To work with the operating system and the files in it, we need the os library. The getpass library will let you know the username on the system, and the platform will determine whether it is Windows or Linux. We connect all the necessary libraries at the very beginning via import and then determine the OS type and username.



import os import getpass import platform type_os = platform.system() usermane = getpass.getuser()
      
      





Creating a dictionary with extensions of popular files and default folders that are associated with them



Using standard Python tools, we create four dictionaries with the most popular file types: music, images, videos and documents.



 video_folder = {".3gp" : "/", ".avi" : "/", ".flv" : "/", ".m4v" : "/", ".mkv" : "/", ".mov" : "/", ".mp4" : "/", ".wmv" : "/", ".webm" : "/"} music_folder = {".mp3" : "/", ".aac": "/", ".flac" : "/", ".mpc" : "/", ".wma" : "/", ".wav" : "/"} pic_folder = {".raw" : "/", ".jpg" : "/", ".tiff" : "/", ".psd" : "/", ".bmp" : "/", ".gif" : "/", ".png" : "/", ".jp2" : "/", ".jpeg" : "/"} doc_folder = {".doc" : "/", ".docx" : "/", ".txt" : "/", ".rtf" : "/", ".pdf" : "/", ".fb2" : "/", ".djvu" : "/", ".xls" : "/", ".xlsx" : "/", ".ppt" : "/", ".pptx" : "/", ".mdb" : "/", ".accdb" : "/", ".rar" : "/", ".zip" : "/", ".7z" : "/"}
      
      





Do not forget that after the folder name the file name will still go, because at the end I have /. New file types are easily added by editing the dictionary.



We ask the user for the name of the download folder



On Windows and Linux, the download folder appears on a system with different names. For Windows, this is regardless of the localization of the Downloads folder, then on Linux distributions this folder is called “Downloads”. In addition, it may happen that the user changes the name of the folder with the downloaded files and you need to ask if the current name of the directory differs from the standard ones.



 if type_os == "Linux": user_downloads_path = input("      ? (-: ) ") or "" if type_os == "Windows": user_downloads_path = input("      ? (-: ) ") or "Downloads"
      
      





The or construct allows you to use the default values ​​in input . That is, if the user has no changes in the name of the folder with downloads, there is no need to do anything, the program itself will substitute the necessary values ​​in the further code.



Set the path to the download folder



Depending on the operating system, the download folder may be located in different places. For Linux, this folder is located on the path / home / username / Downloads / , on Windows it is the path C: / Users / username / Downloads / . In order not to prescribe these paths manually later on, it is easier to create variables in which these paths will be specified.



 if type_os == "Linux": default_path_d = "/home/" + usermane + "/" + user_downloads_path + "/" else: default_path_d_win = r"C:/Users/" + usermane + r"/" + user_downloads_path+ r"/"
      
      





Set the path to the download folder for a specific user



To further use the capabilities of previously connected modules for working with the operating system and files, we must set the path to the download folder using the variables that we created and received earlier.



 if type_os == "Linux": downloads_path = os.listdir("/home/" + usermane + "/" + user_downloads_path) else: downloads_path_win = os.listdir(r"C:/Users/" + usermane + r"/" + user_downloads_path)
      
      





Well, and also for the convenience of further use of the code, we set the path of the form / home folder / username



 if type_os == "Linux": default_path_u = "/home/" + usermane + "/" else: default_path_u_win = r"C:/Users/" + usermane + r"/"
      
      





Check for specific files in the download folder



By enumerating the dictionary, we compare its keys with the file extensions that are in the download folder. If the extension matches the key, then the necessary file must be moved to the corresponding default folder (whose name is the value in the dictionary).



 #      .  ,      for music_format in music_folder: if type_os == "Linux": for name_file in downloads_path: if name_file.endswith(music_format): result = name_file.split(str(music_format), 1) os.rename(default_path_d + result[0] + music_format, default_path_u + music_folder.get(music_format) + result[0] + music_format) if type_os == "Windows": for name_file in downloads_path_win: if name_file.endswith(music_format): result = name_file.split(str(music_format), 1) os.rename(default_path_d_win + result[0] + music_format, default_path_u_win + "Music" + r"/" + result[0] + music_format) #      .  ,      for pic_format in pic_folder: if type_os == "Linux": for name_file in downloads_path: if name_file.endswith(pic_format): result = name_file.split(str(pic_format), 1) os.rename(default_path_d + result[0] + pic_format, default_path_u + pic_folder.get(pic_format) + result[0] + pic_format) if type_os == "Windows": for name_file in downloads_path_win: if name_file.endswith(pic_format): result = name_file.split(str(pic_format), 1) os.rename(default_path_d_win + result[0] + pic_format, default_path_u_win + "Pictures" + r"/" + result[0] + pic_format) #        .  ,      for doc_format in doc_folder: if type_os == "Linux": for name_file in downloads_path: if name_file.endswith(doc_format): result = name_file.split(str(doc_format), 1) os.rename(default_path_d + result[0] + doc_format, default_path_u + doc_folder.get(doc_format) + result[0] + doc_format) if type_os == "Windows": for name_file in downloads_path_win: if name_file.endswith(doc_format): result = name_file.split(str(doc_format), 1) os.rename(default_path_d_win + result[0] + doc_format, default_path_u_win + "Documents" + r"/" + result[0] + doc_format)
      
      





Initially, I planned to solve the problem of finding file extensions by using regular expressions and was engaged in their formulation. But then I read on one of the sites that if you want to solve a problem, then only the last thing you need to use regular expressions. Python has other easier and more intuitive ways to do what is required of you. Therefore, instead of these expressions, the file extension is determined by using the string method endswith () . It takes the key from the dictionary and checks if the file ends with it. Then, using the split () method, only the file name is taken for further movement using os.rename () . As arguments of the latter, all previously created variables are used.



We ask the user what to do with the remaining files



After the necessary files are sorted, the program must either terminate or delete those files that did not fall under the move (for example, exe-files or deb-packages). The decision is made by the user; by default, deletion does not occur.



 #        delete_user_confirm = input('     ?     (-: ) ' or '') if delete_user_confirm == '': if type_os == "Linux": files_to_remove = os.listdir(default_path_d) for remove_files in files_to_remove: os.remove(default_path_d + "/" + remove_files) if type_os == "Windows": files_to_remove = os.listdir(default_path_d_win) for remove_files in files_to_remove: os.remove(default_path_d_win + "/" + remove_files) else: print('  .   .')
      
      





Summarizing



I tried to explain how the program I created worked as clear as possible. But I think that those who want to understand will still review the code itself several times. Perfectionist Organizer is presented in two versions - console and graphical. You can find both on the link to my Github , there are also instructions on how to download and use the program. I ran the console version on my main OS (Archlinux) and the GUI version in a virtual machine on Windows 7. In both cases, the program worked with a bang. I also want to attach a demo of how it works under Linux. If this topic is interesting to someone, then in the next article I will tell you how I made the GUI version and what difficulties I encountered.



Demonstration of the Perfectionist Organizer
image



Future plans



Next in line is a program that will remind you of important events from the Google Sheets table in Telegram. As soon as I finish it I will tell you here. You can leave any questions and feedback on the work of the Perfectionist Organizer in the comments or in PM. Thanks for your attention!



All Articles