import os
os.getcwd()
'/content'
os
ModuleThe os
module helps us access and manipulate the file system.
Detecting the name of the current working directory, using the getcwd
function:
import os
os.getcwd()
'/content'
We see in Google Colab the default working directory is called “content”.
Listing all files and folders that exist in a given directory (for example in the “content” directory where we are right now), using the listdir
function:
"/content") os.listdir(
['.config', 'sample_data']
We see there is a “sample_data” directory.
After further inspection, we see it contains some example text and data files:
"/content/sample_data") os.listdir(
['anscombe.json',
'README.md',
'california_housing_train.csv',
'mnist_train_small.csv',
'mnist_test.csv',
'california_housing_test.csv']
So far we have used an absolute file reference, but since we are already in the “content” directory, it is possible to use a relative file references instead. These references are relative to the “content” directory, where we are right now.
os.listdir()
['.config', 'sample_data']
"sample_data") os.listdir(
['anscombe.json',
'README.md',
'california_housing_train.csv',
'mnist_train_small.csv',
'mnist_test.csv',
'california_housing_test.csv']
For the remainder of this chapter we will continue using relative references, for simplicity.
Checking to see whether a given directory or file exists, using the isdir
and isfile
functions from the os.path
sub-module:
"sample_data") os.path.isdir(
True
"sample_data/README.md") os.path.isfile(
True
= "sample_data/anscombe.json"
filepath
# verifying the file exists:
os.path.isfile(filepath)
True
Deleting a file, using the remove
function:
os.remove(filepath)
# verifying the file was deleted:
os.path.isfile(filepath)
False
Creating a new directory using the makedirs
function:
"my_data", exist_ok=True) os.makedirs(
# verifying the "my_data" directory got created:
os.listdir()
['.config', 'my_data', 'sample_data']
To delete an empty directory, we can use the rmdir
function from the os
module, however it only works for empty directories and throws an error if the directory does not exist. So for a more robust solution, we can use the rmtree
function from the shutil
module:
#os.rmdir("my_data")
from shutil import rmtree
"my_data", ignore_errors=True) rmtree(
# verifying the "my_data" directory got deleted:
os.listdir()
['.config', 'sample_data']