This article will give you a guide on how to work with directories using Python. Firstly I want to show you how you can read and write a file in Python.
In the example above open() opens the file and take in the mode for file manipulation as an argument, ‘r’ is for read which reads content of the file and you can guess ‘w’ is for writing into a file. Note if you write into a file that has contents in it, the previous content will be deleted.
Notice that this file come from a directory which can be a root directory or a subdirectory, below is a representation of a directory tree.
# directory/
# |
# ├── sub_dir/
# | ├── bar.py
# | └── foo.py
# |
# ├── sub_dir_b/
# | └── file4.txt
# |
# ├── file1.py
# ├── file2.csv
# └── file3.txt
To work on directories the built-in os module has a number of useful functions that can be of use of get results. To list the contents of a directory there is os.listdir() method that can be used to get directory listing. Here is an example:
In the above image it shows a Python list containing the contents of the directory. You can print out the output call to os.listdir() using a loop to give a cleaner result:
Another operation that can be performed is the making of a new directory. Doing this is pretty straightforward you need the os.mkdir() method to make a directory.
Note that if the directory already exists os.mkdir() is going to raise a FileExistsError.
You can also create multiple directories using the os.makedirs() method. It takes in the directory names divided with ‘/’ and create directories in a nested directory structure.
# |
# └── rick/
# └── morty/
# └──summer/
The last operation we are going to talk on is deleting files in directories, using methods found in os. These methods and os.remove() and os.unlink(), they are semantically identical.
You can use them like this:
– deleting using os.remove()
– deleting using os.unlink()
Note that this method of file deletion removes it entirely from your system and it can’t be recovered in the recycle bin, so you have to be sure you want to delete the directory or file before you carry on.
The two functions will throw an OSError if the path passed to them is a directory instead of a file. So you can check if that what you try to delete is a file or use exception handling to handle OSError.
os.path.isfile() checks whether data_file is actually a file. If it is, it is deleted by the call to os.remove(). If data_file points to a folder, an error message is printed to the console.
The following example shows how to use exception handling to handle errors when deleting files:
The code above attempts to delete the file first before checking its type. If data_file isn’t actually a file, the OSError that is thrown is handled in the except clause, and an error message is printed to the console. The error message that gets printed out is formatted using Python f-Strings.