- Python rename file: How to rename a file in Python
- Table of contents
- Rename file in Python
- Using os.rename() method to rename file
- Syntax:
- Parameters:
- Input:
- Output:
- Renaming only the Extension of the file in Python
- Input:
- Output:
- Closing thoughts
- Rename Files in Python: A Guide with Examples using os.rename()
- How to Rename a File in Python
- 4 Simple Steps to Rename a File in Python
- 1. Getting the File Path of the File we Want to Rename With Python
- Finding the File Path in Windows
- Finding the File Path in Linux
- 2. Copy the Path of the File to Rename
- 3. Importing the os Module
- 4. Renaming the File
- Changing a Name of a File in Windows
- Renaming a File in Linux
- How to Rename Multiple Files in Python
- Renaming Multiple Files by Replacing Characters in the File Name
- Conclusion: Renaming Files in Python
Python rename file: How to rename a file in Python
There are many instances when you decide to name your file something but later regret it and want to rename the file. It is not as simple as renaming a folder in your computer system, but in Python, renaming a file is a very easy task. In this blog, we will see various methods to rename files.
Table of contents
- Rename file in Python
- Using os.rename() method to rename file
- Renaming only the Extension of the file in Python
- Closing thoughts
Rename file in Python
In order to rename a file, the first thing we need is the path of the file. The path is the location of the file on the disk in a computer system. To be more particular, an Absolute path contains the complete directory list required to locate the file and a Relative path contains the current directory and then the file name.
Using os.rename() method to rename file
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
Python rename() file is a method used to rename a file or a directory in Python programming and can be declared by passing two arguments named src (Source) and dest (Destination).
Syntax:
os.rename(src, dest, *, src_dir, dest_dir)
Parameters:
src: A path-like object representing the file system path. This is the source file path that is to be renamed.
dest: Destination is the new name of the file or directory you want to change.
src_dir: Source file directory is an optional parameter telling where the file is stored.
dest_dir: The destination file directory is also an optional parameter telling where the renamed file should be saved on the disk.
Input:
# importing the os module import os # Source src = 'filee.text' # Destination dest = 'file.txt' # Renaming the file os.rename(src, dest) print ("The file has been renamed.")
Output:
The file has been renamed.
This method does not have any return type.
Keep in mind if the «dest» already exists then the FileExistsError will be thrown in Windows and in the case of UNIX, an OSError will be thrown.
Renaming only the Extension of the file in Python
Sometimes you might want to rename the extension of your file and this can be quickly done using rename() method in Python. This can be done by selecting the file and then getting only the file name using the splitext() method of the os module.
This method returns the root and extension separately. Once we get the root/base of the filename, we can add the new extension to it while renaming it using the rename() method.
Input:
import os # Selecting the list print('Before rename:') file = file.txt print(file) # Renaming the file for file_name in file: # construct full file path old_file_name = os.path.join(folder, file_name) # Change the extension from txt to pdf new_file_name = old_file_name.replace('.txt', '.pdf') os.rename(old_file_name, new_file_name) print('After rename:') print(file)
Output:
Before rename: file.txt After rename: file.pdf
Closing thoughts
Renaming a file in Python is as easy as naming a file. The Os module in Python is used to rename a file name and other functions. One can learn more about other Python data types here.
Rename Files in Python: A Guide with Examples using os.rename()
This post provides a step-by-step guide on how to rename files in Python. The post explains how to rename a single file in Python in four simple steps. First, you need to get the file path of the file that you want to rename. Second, copy the path of the file to rename. Third, import the os module, a built-in Python module that provides a way of using operating system-dependent functionality. Finally, use the os module to rename the file.
The post also provides instructions on how to rename multiple files in Python. It explains that one way to rename multiple files is to replace characters in the file name. This can be done by looping through the files in a directory and using the string method replace() to replace the characters in the file name.
How to Rename a File in Python
For instance, if we have a file called python-rename-files.txt we need to know where we have stored it. There are, of course, different ways to do this. We can either place the Python script in the same directory or just run it to rename the file. Here’s a simple example of how to rename a file in Python:
import os os.rename('python-rename-files.txt', 'renamed-file.txt')
Code language: Python (python)
4 Simple Steps to Rename a File in Python
In the first section, we will learn how to rename a single file in Python step-by-step. Now, the general procedure is similar when we are using Linux or Windows. However, how we go about the first step to rename a file in Python may differ depending on which OS we use. In the renaming a file in Python examples below, we will learn how to carry on and change names both in Linux and Windows.
1. Getting the File Path of the File we Want to Rename With Python
First, to get Python to rename a file, Python needs to know where the file is located. That is, step 1 is finding the location of the file we want to change the name on.
That is, if we store our Python scripts (or Jupyter notebooks) in certain directories, we need to tell Python the complete path to the file we want to rename.
Finding the File Path in Windows
If we use Windows, we can open up File Explorer. First, go to the folder where the file is located (e.g., “Files_To_Rename”) and click on the file path (see image below). It should look something like “C:\Users\erima96\Documents\Files_To_Rename”.
Finding the File Path in Linux
Now, if we are to rename a file, using Python, in Linux, we need to know the path. There are, of course, many methods to find the file path in Linux. One method is to open up a Terminal Window and use the readlink and xclip command-line applications:
readlink -f FILE_AND PATH | xclip -i
Code language: Bash (bash)
For instance, if the file we want to rename with Python is located in the folder “/home/jhf/Documents/Files_To_Rename/python-rename-files.txt” this is how we would do it:
2. Copy the Path of the File to Rename
Second, we copy the path of the file we want to rename. Note, this is as simple as just right-clicking on the path we already have marked:
3. Importing the os Module
Third, we need to import a Python module called os. Luckily, this is very easy and we type: import os. In the next step, we will rename a file using Python!
4. Renaming the File
Finally, we are ready to change the file name using the os module from Python. As the file path can be long we will create a string variable first and then rename the file using os.rename. Here’s how to rename a file using Python: os.rename(PATH_TO_THE_FILE, PATH_TO_THE_NEW_FILE)
Changing a Name of a File in Windows
Here’s a full code example, for Windows users, on how to change the name of a file using Python:
import os file_path = 'C:\\Users\\erima96\\Documents\\Files_To_Rename\\' os.rename(file_path + 'renamed-file.txt', file_path + 'python-rename-files.txt')
Code language: Python (python)
Note how we added an extra ”\” to each subfolder (and at the end). In the os.rename method we also added the file_path to both the file we want to rename and the new file name (the string variable with the path to the file) and added the file name using ‘+’. If we don’t do this, the file will also be moved to the Python script folder. If we run the above code, we can see that we have successfully renamed the file using Python:
Renaming a File in Linux
Here’s how to rename the file in Linux. Note the file path will be a bit different (as we saw earlier when we found the file path):
import os file_path = '/home/jhf/Documents/Files_To_Rename/python-rename-files.txt' os.rename(file_path + 'renamed-file.txt', file_path + 'python-rename-files.txt')
Code language: Python (python)
Now that we have learned how to rename a file in Python, we will continue with an example in which we change the name of multiple files. As previously mentioned, renaming multiple files can be useful if we have many files that need new names.
How to Rename Multiple Files in Python
In this section, we will learn how to rename multiple files in Python. There are, of course, several ways to do this. One method could be creating a Python list with all the file names we want to change. However, if we have many files, this is not an optimal way to change the name of multiple files. Thus, we will use another method from the os module; listdir. Furthermore, we will also use the filter method from the module called fnmatch.
The first step, before renaming the files, is to create a list of all text files in a folder (e.g., in the subfolder “Many_Files”). Note, that we have added the subfolder to the file_path string.
import os, fnmatch file_path = 'C:\\Users\\erima96\\Documents\\Files_To_Rename\\Many_Files\\' files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt') print(files_to_rename)
Code language: Python (python)
Next, we will loop through each file name and rename them. In the example below, we are using the file_path string from the code chunk above because this is where the files are located. If we were to have the files we want to rename in a different folder, we’d change file_path to that folder. Furthermore, we are creating a new file name (e.g., new_name = ‘new_file’), and we use the enumerate method to give them a unique name. For example, the file ‘euupbihlaqgk.txt’ will be renamed ‘Datafile1.txt’.
new_name = 'Datafile' for i, file_name in enumerate(files_to_rename): new_file_name = new_name + str(i) + '.txt' os.rename(file_path + file_name, file_path + new_file_name)
Code language: Python (python)
As can be seen in the rename a file in Python example above, we also used the str() method to change the data type of the integer variable called i to a string.
Remember, if we were using Linux, we’d have to change the file_path so that it would find the files we want to rename.
Now, there are other useful functions in Python. For instance, if we need to get the absolute value in Python, we can use the abs() function.
Renaming Multiple Files by Replacing Characters in the File Name
Now, sometimes we have files that we want to replace certain characters. In this final example, we will use the replace method to replace underscores (“_”) from file names. This, of course, means that we need to rename the files.
import os, fnmatch file_path = 'C:\\Users\\erima96\\Documents\\Files_To_Rename\\Many_Files\\' files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt') for file_name in files_to_rename: os.rename(file_path + file_name, file_path + file_name.replace(' ', '-'))
Code language: Python (python)
Now, in the code above we have successfully replaced the “_” from the filenames using replace and then renamed the files. Again, remember if we rename files in Linux, the file_path string needs to be changed (e.g., ” “).
Conclusion: Renaming Files in Python
In this post, you have learned how to rename files in Python for both a single file and multiple files. By following the step-by-step instructions in this post, you can easily change the names of files in a directory and save time and effort. Python’s built-in os module provides a convenient and efficient way of renaming files, and this post has explained how to use this module for this purpose.
Renaming files in Python can be useful for various programming projects, and this post has provided a beginner-friendly guide for anyone looking to rename files in Python. With the instructions and code examples provided in this post, you can confidently apply these techniques to your projects and modify file names to suit your needs.
Remember, commenting and sharing on social media is a great way to engage with the community and show support for the content that you find valuable. So, if you found this post helpful, why not share it with others who might benefit from it? And do not forget to leave a comment below to let me know how this post has helped you in your Python programming journey!