Renaming and deleting files and accessing directories

In Python, system-level access to file directories and various other operating system commands is provided by the os module. The os module is a very powerful utility. In this section, we will see a few of its uses with respect to renaming, deleting, creating, and accessing directories with the help of the following snippet from the os_directories.py file:

The code snippet in the preceding screenshot shows the various ways in which the os module is used with files and directories in Python, in order to rename and delete files and create and change directories. It also showed us how we can rename and traverse all the files (including nested files) from a subfolder. It should be noted that if we wish to delete a folder, we can use the os.rmdir() method, but all the files of the folder should be explicitly deleted in order for this to work:

  • The following output shows what happens with the file before and after its creation:

  • The following output shows the change in the file name:

  • The following output shows the change after the file is removed:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset