Python os.fchdir() 方法



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

示例 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

示例 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
python_file_methods.htm
廣告
© . All rights reserved.