11- Directories and files

11- Directories and files

os module functions:

    • os.getcwd(): obtains the current working directory.

      • os.chdir(dir): changes the current working directory to dir.

      • os.listdir(dir="."): lists files in the directory dir.

      • os.path.exists(path): checks whether the path exists.

To print the current directory:

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

To 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 )

To list all files in the home directory:

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

If you find this content helpful, please consider SUBSCRIBING to my channel for future updates.

If you would like to get the full video tutorial and a certificate, you can enroll in the course by following this link: https://www.udemy.com/course/python-for-researchers/?referralCode=886CCF5C552567F1C4E7