Automate Renaming and Organizing Files with Python

We tend to know how to rename and organize files with Python, hence, the article split this process into two parts: one for explaining a way to organize files and the second part is to know the way to rename files.

Here we are going to find out about a way to rename and organize files in Python. we are going to use completely different modules like os and shutil. we are going to be automating the tasks of moving our downloaded files to the various folders in keeping with their file sorts.

What is OS module?

This module helps move with the package and provides how of victimization os dependent functionalities. it’s several functions such startfile(), getcwd() and lots of additional. during this article, we are going to use the listdr() and also the path.isfile() functions.

What is shutil module?

This module offers variety of high-level operations on files and assortment of files. Using it, we will move, copy and rename our files. it’s several helpful functions like copyfile(), copymode(), etc. during this article, we are going to use the move() methodology of the shutil module to maneuver our files from one place to a different.

Note: os and shutil modules come under Python standard library therefore, we tend to don’t got to install them by pip command we we are just simply importing them in our program.

Syntax of shutil.move()
It recursively moves a file or directory from one place to a different, then returns the ultimate destination. Src is placed into the destination directory if it already exists. counting on the linguistics of os.rename(), a destination that already exists however isn’t a directory could also be overwritten.

Syntax: shutil.move(source, destination, copy_function = copy2)

Parameters:
source: path of the supply destination directory
destination: path of the destination directory
copy_function (optional): the default worth of this parameter is copy2. we will use alternative copy perform like copy, copytree, etc for this parameter.

Return Value: This methodology returns a string that represents the trail of fresh created file.

Automate organizing file victimization Python
To alter organizing files in python first we’ve to import the desired modules that square measure os and shutil then we’ve to assign the directories we’ll be operating to applicable variables and so create classes of files with the assistance of tuples like docs, pictures and code. at that time we’ve to create a listing of all files gift in root directory(In our case root directory is Downloads folder) victimization for loop and strategies provided in os module. in conclusion we’ve to maneuver all the files gift in downloads folder into their various folders victimization move perform of shutil module.

Before running the code we’ll got to produce five folders within the downloads folder: pictures, documents, software, others, and a Log folder that may store the Log.txt file generated by our Python program. once running the program, we will see that there’s nothing however five folders that we tend to created within the downloads folder, and within these five folders square measure the various files.

NOTE: Before running the script, modification the directory to Downloads by typewriting cd Downloads within the terminal.

We suppose that we want to organize the files in the download folder on our computer machine. So we will use the following code to automate this task.

# importing required modulesimport osfrom shutil import move# making the directoriesroot_dir = "C:\\Users\\[Username]\\Downloads"image_dir = "C:\\Users\\[Username]\\Downloads\\images"documents_dir = "C:\\Users\\[Username]\\Downloads\\documents"others_dir = "C:\\Users\\[Username]\\Downloads\\others"software_dir = "C:\\Users\\[Username]\\Downloads\\softwares"# files types of each categorydocs = ('.docx', '.doc', '.txt', '.pdf','.xls', '.ppt', '.xlsx', '.pptx')images = ('.jpg', '.jpeg', '.png', '.svg','.tif', '.tiff', '.gif',)softwares = ('.exe', '.dmg', '.pkg')# appending all the files in the root directory to files[]files = []for f in os.listdir(root_dir):if os.path.isfile(f) and not f.startswith('.') and not f.__eq__(__file__):files.append(f)# moving files to the respective folders,# overwriting if neededfor file in files:if file.endswith(docs):move(file, documents_dir**+"/"+file)elif file.endswith(images):move(file, image_dir+"/"+file)elif file.endswith(softwares):move(file, software_dir+"/"+file)else:move(file, others_dir+"/"+**file)

Using Python, rename files automatically:

The paths to the files must first be initialized into a separate variable before being passed as an argument to the rename() function in order to automate file renaming using Python. Utilize the path.isfile() function of the os module to see if the file with the ‘new name’ already exists. Print a message if it does; otherwise, simply rename the old file to the new file.

Os.rename syntax ()

The OS module is responsible for this function. Renaming files is done with it. What follows is the syntax:

Syntax: src dir fd = None, dst dir fd = None, os.rename(source, destination, *)

Parameters:

source: An object that resembles a path and represents the file system path. This is the path to the source file that has to be renamed.
destination: An object that resembles a path and represents the file system path.
A file descriptor relating to a directory is called src dir fd (optional).
A file descriptor relating to a directory is called dst dir fd (optional).

# importing the required modulesimport osold = "C:\\Users\\[USERNAME]\\Desktop\\old_name.txt"new = "C:\\Users\\[USERNAME]\\Desktop\\newname.txt"# check if the file with the new name already existsif os.path.isfile(new):print("file already exists")else:# rename the file to the new name# if file doesn't existos.rename(old, new) "

Follow me on YouTube: http://www.youtube.com/c/TemotecLearningAcademy/?sub_confirmation=1

Follow me on Medium: https://medium.com/@temoteclearningacademy

Follow me on Quora: https://temotecacademy.quora.com/?invite_code=ZIeeqxfcztMR4vRITASN

Follow me on LinkedIn:

https://www.linkedin.com/in/temotec-learning-academy-0a615a17a/

Check & try all my courses :

1-Python for Beginners :Learn Python Basics by Python Projects

https://www.udemy.com/course/the-complete-python-for-beginner-master-python-from-scratch/?referralCode=A17413F047D0E511C848

2-Python OOP: Python Object Oriented programming with Projects

https://www.udemy.com/course/python-oop-master-python-oop-from-scratch-with-projects/?referralCode=74EFC0268F5D1A6BDDEB

3-Python challenging coding Exercises & MCQ : become job ready:

https://www.udemy.com/course/python-exercises-workbook/?referralCode=F523A274F49489AA1CC2

4- SQL for Data Analysis and Data Science in 2021:

https://www.udemy.com/course/sql-course-for-data-science/?referralCode=1E3D3DAFA2FA3E00ECCB

5- SQL Introduction: SQL Crash Course.:

https://www.udemy.com/course/sql-course/?referralCode=9E796BE2746262D9A996

6- Data Analyst Bootcamp: Complete Course to be a Data Analyst:

https://www.udemy.com/course/data-analyst-bootcamp/?referralCode=3C7125445BBF082413AD

7- Learn Python By building Games in Python:

https://www.udemy.com/course/python-games-development/?referralCode=EDC3B04398C25A03E96F

8- SQL Bootcamp: Complete SQL Course:

https://www.udemy.com/course/sql-bootcamp-course/?referralCode=00A8AF336E71B2858361

9- Python Pandas Data Crash Course:

https://www.udemy.com/course/python-pandas-data-crash-course/?referralCode=73C6F6325067BE8EC7BE

10- Facebook Chat Bot in Python from Scratch:

https://www.udemy.com/course/facebook-chat-bot-in-python/?referralCode=0FAFD44C9933DFAE708B

11- Twitter Chat Bot in Python from Scratch:

https://www.udemy.com/course/twitter-chat-bot-in-python/?referralCode=16EC6263C1E33BBABB42

12- Numpy Pandas in Python from Scratch:

https://www.udemy.com/course/numpy-pandas-python/?referralCode=B93F13A53750E215F3D9

13- Python Data Course: Python for Data Analysis & Visualization

https://www.udemy.com/course/python-data-analysis-visualization-course/?referralCode=8F647705760CD9F5933F

14- JavaScript Crash Course:

https://www.udemy.com/course/javascript-crash-course-bootcamp-projects/?referralCode=3DF82E17FA7A9744807D

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐