Python | os.fchdir() method
Last Updated :
18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.fchdir()
method in Python is used to change the current working directory to the directory represented by the given file descriptor.
A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. A File descriptor is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc.
For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2.
Further files opened by the current process will get the value 3, 4, 5 an so on.
os.fchdir()
method is equivalent to os.chdir(file_descriptor)
method.
Syntax: os.fchdir(fd)
Parameter:
fd: A file descriptor. The file descriptor must represent an opened directory not an open file.
Return Type: This method does not return any value.
Code #1: Use of os.fchdir() method to change the current working directory
import os
print ( "Current working directory:" , os.getcwd())
path = "/home/ihritik/Documents"
fd = os. open (path, os.O_RDONLY)
os.fchdir(fd)
print ( "Current working directory changed" )
print ( "Current working directory:" , os.getcwd())
|
Output:
Current working directory: /home/ihritik
Current working directory changed
Current working directory: /home/ihritik/Documents
Code #2: Possible errors while using of os.fchdir() method
import os
path = "/home/ihritik/Documents/file.txt"
fd = os. open (path, os.O_RDONLY)
os.fchdir(fd)
print ( "Current working directory changed" )
print ( "Current working directory:" , os.getcwd())
|
Output:
Traceback (most recent call last):
File "changeDir.py", line 24, in
os.fchdir(fd)
NotADirectoryError: [Errno 20] Not a directory
Code #3: Handling possible errors while using of os.fchdir() method
import os
path = "/home/ihritik/Desktop/file.txt"
try :
fd = os. open (path, os.O_RDONLY)
try :
os.fchdir(fd)
print ( "Current working directory changed" )
print ( "Current working directory:" , os.getcwd())
except NotADirectoryError:
print ("The given file descriptor does \
not represent a directory")
except FileNotFoundError:
print ( "Path does not exists" )
except PermissionError:
print ( "Permission denied" )
|
Output:
The given file descriptor does not represent a directory
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...