Python From Beginner to Advanced

0% completed

Previous
Next
Python - Renaming and Deleting Files

Renaming and deleting files are common operations when managing file systems. Python provides built-in support for these actions through the os module, which includes functions like os.rename() for renaming files and os.remove() for deleting files.

Renaming Files

Renaming files is useful for organizing file systems, applying naming conventions, or updating file names based on new information.

Use Case: Ideal for batch renaming of files, such as timestamping logs or updating references after a project's rebranding.

Example

Python3
Python3
. . . .

Explanation:

  • import os: Imports the Python module os which provides a portable way of using operating system-dependent functionality.
  • current_file_name = 'old_name.txt': Defines the variable current_file_name with the value 'old_name.txt', which is the current name of the file to be renamed.
  • new_file_name = 'new_name.txt': Defines the variable new_file_name with the value 'new_name.txt', which will be the new name of the file after renaming.
  • os.rename(current_file_name, new_file_name): Calls the rename() method from the os module to rename the file from old_name.txt to new_name.txt.
  • print(f"File renamed from {current_file_name} to {new_file_name}"): Outputs a message to the console indicating that the file has been successfully renamed.

Deleting Files

Deleting files is necessary when cleaning up disk space or removing unnecessary or outdated files.

Use Case: Useful for maintaining file storage efficiency, such as removing temporary files or clearing old data that is no longer needed.

Example

Python3
Python3
. . . .

Explanation:

  • import os: This line imports the os module, necessary for file deletion functionality.
  • file_name = 'file_to_delete.txt': Sets the variable file_name with the string 'file_to_delete.txt', identifying the file to be deleted.
  • os.remove(file_name): Uses the remove() function from the os module to delete the specified file.
  • print(f"{file_name} has been deleted"): Prints a confirmation message stating that the file has been successfully deleted.

These examples illustrate how to use Python's os module to rename and delete files effectively, demonstrating essential file management operations that are widely applicable in various programming and data management scenarios.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next