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:
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:
We see there is a “sample_data” directory.
After further inspection, we see it contains some example text and data files:
['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.
['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:
See the Text File Operations chapter for examples of how to read and write text files using the open function.
See Getting Started with Pandas for examples of how to read and write tabular data files using the pandas package.
Deleting a file, using the remove function:
Creating a new directory using the makedirs function:
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: