Python Directory
A directory or a folder is a storage space containing files and subdirectories. We can work with directories using Python's OS module.
Getting Current Directory
We can use the getcwd()
function of the os module if we want to get the path to our current directory.
import os
current_dir = os.getcwd()
print(current_dir)
When you run the code, you get the current working directory of the Python code file you are working on.
Changing Directory
We can use the chdir()
function in Python to change the current working directory. Let us change our directory to C:\Python
.
import os
current_dir = os.getcwd()
print(current_dir)
os.chdir("C:\Python")
print(os.getcwd())
When you run the above code, you will see the program return both your current directory and the new changed directory.
If we now create a file with the open()
function in write mode, it will be created inside the new directory.
If you want to learn about Python files, visit Python Files Input and Output.
Note: Do create a Python folder in the C drive before running the code above.
Listing all Directories and Files
We can use the listdir()
function of the os module to list all the files, and sub-directories
Here is an example:
import os
print(os.listdir())
When you run this function, it will return a list of all the files and folders present in your current working directory.
Suppose you want a list of files and folders present in another directory (not your current working directory). In that case, you can use the following code:
import os
print(os.listdir("<path>"))
Making a New Directory
The mkdir()
function of the os module allows us to create a new directory.
import os
os.mkdir("test")
Here, the mkdir function creates a new directory named test in our current directory.
Renaming a Directory or a File
The rename()
function of the os module allows you to rename any directory or file. This function takes two arguments:
- old name of the file or directory
- new name of the file or directory
import os
# rename directory or file
os.rename('<old_name>', '<new_name>')
Removing Directory or File
The remove()
function of the os module lets you remove any file.
For example,
import os
print(os.listdir())
os.remove("<filename>")
print(os.listdir())
In the above code,
print (os.listdir())
- Prints a list of all the files and folders.os.remove('<filename>')
- Removes a particular directory.print (os.listdir())
- Prints the directory again but without the file we have deleted
In a similar fashion, we can also remove directories using the rmdir()
function.
import os
print(os.listdir())
os.rmdir("<path_to_directory>")
print(os.listdir())
The above code will remove any directory whose path you have mentioned in the rmdir()
function.
Recommended Reading: Python Modules