How To Know Python Directory

In this tutorial, we will cover the basics of working with Python directories and understanding the various ways to know and navigate directory paths in Python.

Knowing the Python directory is essential for reading, writing, and organizing files effectively. We will be using some built-in Python libraries and functions to perform these tasks.

Step 1: Importing the necessary libraries

To get started, we will need to import the os library, which provides a way of using operating system-dependent functionality like reading or writing to the file system.

Step 2: Knowing the current working directory

To know the current working directory, use the os.getcwd() function.

The above code will output the current working directory as a string.


Step 3: Changing the current working directory

To change the current working directory, use the os.chdir() function and pass the path of the desired directory.

The output should display the new working directory.


Step 4: Listing the contents of a directory

To list the contents of a directory, use the os.listdir() function. By default, it will list the contents of the current working directory, or you can provide a specific path as an argument.

The above code will output a list of all the files and directories in the current working directory.

['file1.txt', '', 'folder1', 'folder2']

Step 5: Creating a new directory

To create a new directory, use the os.makedirs() function and pass the desired directory name.

The output will now include the newly created directory.

['file1.txt', '', 'folder1', 'folder2', 'new_folder']

Full Code


In this tutorial, we have learned how to know the Python directory, change the working directory, list its contents, and create a new directory using the os library. These basic operations are essential for working with files and directories in Python.

You can further explore the os library functions to perform more advanced operations on directories and files. Check the official Python documentation for more information.