(Python Tutorial – 029)
Python Directory and Files Management
In this tutorial, you’ll learn about file and directory management in Python, i.e. creating a directory, renaming it, listing all directories, and working with them.
If there are a large number of files to handle in our Python program, we can arrange our code within different directories to make things more manageable.
A directory or folder is a collection of files and subdirectories. Python has the
os module that provides us with many useful methods to work with directories (and files as well).
Get Current Directory
We can get the present working directory using the
getcwd() method of the
This method returns the current working directory in the form of a string. We can also use the
getcwdb() method to get it as bytes object.
import os os.getcwd() 'C:\Program Files\PyScripter' os.getcwdb() b'C:\Program Files\PyScripter'
The extra backslash implies an escape sequence. The
print() function will render this properly.
print(os.getcwd()) C:Program FilesPyScripter
We can change the current working directory by using the
The new path that we want to change into must be supplied as a string to this method. We can use both the forward-slash
/ or the backward-slash to separate the path elements.
It is safer to use an escape sequence when using the backward slash.
'C:\Python33') print(os.getcwd()) C:Python33os.chdir(
List Directories and Files
All files and sub-directories inside a directory can be retrieved using the
This method takes in a path and returns a list of subdirectories and files in that path. If no path is specified, it returns the list of subdirectories and files from the current working directory.
print(os.getcwd()) C:Python33 os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools'] os.listdir('G:\') ['$RECYCLE.BIN', 'Movies', 'Music', 'Photos', 'Series', 'System Volume Information']
Making a New Directory
We can make a new directory using the
This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.
'test') os.listdir() ['test']os.mkdir(
Renaming a Directory or a File
rename() method can rename a directory or a file.
For renaming any directory or file, the
rename() method takes in two basic arguments: the old name as the first argument and the new name as the second argument.
'test'] os.rename('test','new_one') os.listdir() ['new_one']os.listdir() [
Removing Directory or File
A file can be removed (deleted) using the
rmdir() method removes an empty directory.
'new_one', 'old.txt'] os.remove('old.txt') os.listdir() ['new_one'] os.rmdir('new_one') os.listdir() os.listdir() [
rmdir() method can only remove empty directories.
In order to remove a non-empty directory, we can use the
rmtree() method inside the
'test'] os.rmdir('test') Traceback (most recent call last): ... OSError: [WinError 145] The directory is not empty: 'test' import shutil shutil.rmtree('test') os.listdir() os.listdir() [
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.