Python os.fchdir() 方法

Python File(檔) 方法 Python OS 檔/目錄方法


概述

os.fchdir() 方法通過檔描述符改變當前工作目錄。

Unix, Windows 上可用。

語法

fchdir()方法語法格式如下:

os.fchdir(fd);

參數

  • fd -- 檔描述符

返回值

該方法沒有返回值。

實例

以下實例演示了 fchdir() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 首先到目錄 "/var/www/html"
os.chdir("/var/www/html" )

# 輸出當前目錄
print "當前工作目錄為 : %s" % os.getcwd()

# 打開新目錄 "/tmp"
fd = os.open( "/tmp", os.O_RDONLY )

# 使用 os.fchdir() 方法修改到新目錄
os.fchdir(fd)

# 輸出當前目錄
print "當前工作目錄為 : %s" % os.getcwd()

# 關閉打開的目錄

os.close( fd )

執行以上程式輸出結果為:

當前工作目錄為 : /var/www/html
當前工作目錄為 : /tmp

Python File(檔) 方法 Python OS 檔/目錄方法