Python os.fchdir() 方法将当前工作目录更改为文件描述符表示的目录。描述符必须引用打开的目录,而不是打开的文件。
执行所有命令的目录称为当前工作目录。它可以是数据库文件、文件夹、库或目录。当前工作目录也称为当前工作目录或简称为工作目录。此方法不返回任何值。
注意:此方法仅在 UNIX/LINUX 平台中可用。
语法
以下是 Python os.fchdir() 方法的语法 -
os.fchdir(fd)
参数
- fd − 这是一个目录描述符。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.fchdir() 方法的用法。在这里,当前工作更改为由文件描述符 'fd' 表示的目录 “/tmp”。getcwd() 方法用于了解文件的当前工作目录。
import os, sys
# First go to the "/var/www/html" directory
os.chdir("/var/www/html" )
# Print current working directory
print ("Current working dir : %s" % os.getcwd())
# Now open a directory "/tmp"
fd = os.open( "/tmp", os.O_RDONLY )
# Use os.fchdir() method to change the dir
os.fchdir(fd)
# Print current working directory
print ("Current working dir : %s" % os.getcwd())
# Close opened directory.
os.close( fd )
当我们运行上述程序时,它会产生以下结果——
Current working dir : /var/www/html
Current working dir : /tmp
Current working dir : /tmp
示例 2
如果文件描述符表示打开的文件而不是打开的目录,则此方法会引发 'NotADirectoryError' 异常。
import os
path = "code.txt"
# opening the above path
# getting the file descriptor associated with it
filedesc = os.open(path, os.O_RDONLY)
# Changing the working directory
os.fchdir(filedesc)
print("Current working directory is changed succesfully")
# Printing the working directory
print("The current working directory is:", os.getcwd())
在执行上述代码时,我们得到以下输出 -
Traceback (most recent call last):
File "/home/sarika/Desktop/chown.py", line 7, in <module>
os.fchdir(filedesc)
NotADirectoryError: [Errno 20] Not a directory
File "/home/sarika/Desktop/chown.py", line 7, in <module>
os.fchdir(filedesc)
NotADirectoryError: [Errno 20] Not a directory
示例 3
在这里,我们尝试使用 os.fchdir() 方法处理可能的错误。
import os
filepath = "code.txt"
# opening the above path
# getting the file descriptor associated with it
try :
filedesc = os.open(filepath, os.O_RDONLY)
# Changing the working directory
try :
os.fchdir(filedesc)
print("Current working directory is changed successfully")
# Printing the working directory
print("The current working directory is:", os.getcwd())
# If file descriptor does not represents a directory
except NotADirectoryError:
print("The provided file descriptor does not represent an opened directory")
# If the file path does not exists
except FileNotFoundError:
print("The file path does not exists")
# permission related issue while opening the provided path
except PermissionError:
print("Permission is denied")
以下是上述代码的输出 -
The provided file descriptor does not represent an opened directory