Python Directory and Files Management
Managing Directory and Files in Python
If our Python software has a large number of files to handle, we can organise our code into multiple folders to make things easier to manage.
A directory, often known as a folder, is a grouping of files and subdirectories. The OS module in Python provides numerous helpful methods for working with directories (and files as well).
How to Change Directory in Python?
Using the chdir() technique, we can change the current working directory. The new route that we wish to change must be sent to this function as a string.
To separate route items, we can use either the forward-slash (/) or the backward-slash (\). When utilising the backward slash, it is safer to utilise an escape sequence.
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
Python List Directories and Files
The listdir() function can be used to obtain all files and subdirectories within a directory. This function accepts a path and returns a list of its subdirectories and files. If no path is specified, it provides a 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']
How to Create a New Directory in Python?
The function mkdir() is utilised to make a new directory in Python. The path to the new directory is sent to this procedure.
The new directory is made in the current working directory if the complete path is not supplied.
>>> os.mkdir('test')
>>> os.listdir()
['test']
How to Rename a Directory or File in Python?
A file can be renamed using the rename()
function. The rename()
function accepts two basic arguments to rename any directory or file: the old name as the initial argument and the new name as the next argument.
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']
How to Remove Directory or File in Python?
This function can be used to remove or delete a file. The rmdir()
function, on the other hand, removes an empty directory.
>>> os.listdir()
['new_one', 'old.txt']
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
>>> os.rmdir('new_one')
>>> os.listdir()
[]
QUIZ!
