Azad Rasul
SmartRS

SmartRS

11- Directories and files

Azad Rasul's photo
Azad Rasul

Published on Jun 27, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

os module functions:

  • os.getcwd() obtains current working directory
  • os.chdir(dir) changes current working directory to dir
  • os.listdir(dir=".") list files in directory dir
  • os.path.exists(path) checks whether path exists

Print current directory:

import os # import modules
print (os.getcwd()) # e.g., "C:\Users\Azad"

Change the current directory to the home directory:

import os, os. path # import modules
home_dir = os.path.expanduser ("~") # get home directory
print(home_dir)
os.chdir (home_dir )

List all files in the home directory:

print(os.listdir()) 
# ['$netrc', '.anaconda', '.bash_history', '.bundle', ...]
 
Share this
Proudly part of