Python Directory Management
Python Directory Management
Renaming a directory:
os.rename(src, dst): Renames a directory (or file) from src to dst. The source
(src) must exist and the destination (dst) should not already exist.
For example, consider there is a file named ‘file1.txt’ in current working directory.
Now to just rename it :
os.rename("my_directory", "renamed_directory")
If renaming and moving the file to some other directory is required, then the code
snippet should be:
import os
os.renames('my_directory', 'renamed_directory')
Changing Current Working Directory (CWD)
os.chdir(path): Changes the current working directory to the specified path. After
changing, all relative paths are resolved concerning the new working directory. If
the specified path does not exist, an OSError is raised.
import os
print("Current directory :", os.getcwd())
# Changing directory
os.chdir('/home/nikhil/Desktop/')
print("Current directory :", os.getcwd())
Get Size of the Directory
os.path.getsize(path): Returns the size of a file in bytes. Use this with os.walk() to
calculate directory size. os.walk() iterates through all subdirectories and files in a
directory.Summing up file sizes gives the total directory size.
import os
print(os.path.getsize(os.getcwd()))
………………………………………………………………………………………………………………….
import os
import os
#print("Current directory :", os.getcwd()) print("Current directory :", os.getcwd())
# Changing directory
#os.chdir('e:\\skd') os.chdir('e:\\alpha')
print("Current directory :", os.getcwd()) print("Current directory :", os.getcwd())
os.rmdir('e:\\alpha')