Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

How to work with directory in python?

Description

To handle the exception while handling the file using python3.

Process
Current directory

  We can get the present working directory using the getcwd() method.

  This method returns the current working directory in the form of a string.

Change directory

  We can change the current working directory using the chdir() method.

  We can use both forward slash (/) or the backward slash (\) to separate path elements.

Create new directory

  We can make a new directory using the mkdir() method.

  If the full path is not specified, the new directory is created in the current working directory.

Rename a directory

  We can rename a directory by using rename().

Remove a directory

  We can remove a directory by using rmdir().

Sample Code

#import os library
import os
print(“Default directory”)
print(os.getcwd())
print(“\n”)

#change the current directory
os.chdir(‘/home/soft27/soft27/Python’)
print(“Changed directory”)
print(os.getcwd())
print(“\n”)

#create a new directory
os.mkdir(‘new files’)
print(“***New Directory***”)
print(os.listdir())
print(“\n”)

#renaming a directory
os.rename(‘new files’,’new python files’)
print(“***Remnamed directory***”)
print(os.listdir())
print(“\n”)

#removing a directory
os.rmdir(‘new python files’)
print(“***Removed directory***”)
print(os.listdir())

Screenshots
work with directory in python