DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

11- Manage directories and files in Python

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"
Enter fullscreen mode Exit fullscreen mode

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 )
Enter fullscreen mode Exit fullscreen mode

List all files in the home directory:

print(os.listdir()) 
# ['$netrc', '.anaconda', '.bash_history', '.bundle', ...]
Enter fullscreen mode Exit fullscreen mode

If you like the content, please SUBSCRIBE to my channel for future content.

To get full video tutorial and certificate, please, enroll in the course through this link: https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7

Top comments (0)