Python os.getcwd() 方法



Python 的getcwd() 方法代表獲取當前工作目錄。顧名思義,它返回程序的當前工作目錄。呼叫此方法時,它會顯示一個字串,表示我們當前正在工作的目錄的路徑。

語法

getcwd() 方法的語法如下所示:

os.getcwd()

引數

Python 的os.getcwd() 方法不接受任何引數。

返回值

Python 的os.getcwd() 方法返回一個字串,表示當前工作目錄的路徑。

示例

以下示例演示了 getcwd() 方法的用法。在這裡,我們將返回值傳遞給 print 語句以顯示結果。

#!/usr/bin/python
import os, sys

# First go to the required directory
os.chdir("/home/tp/Python/tmp/new" )

# Then print current working directory
print ("Current working dir : %s" % os.getcwd())

執行以上程式時,會產生以下結果:

Current working dir : /home/tp/Python/tmp/new

示例

此示例將使用“os.chdir()”方法將當前工作目錄更改為“/tmp”,然後列印新工作目錄的路徑以驗證更改。

#!/usr/bin/python
import os, sys

# First go to the desired directory
os.chdir("/home/tp/Python/tmp" )

# Print current working directory
print ("Current working dir : %s" % os.getcwd())

# Now open a directory "/home"
fd = os.open( "/home", 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 )
print("Closed successfully!!")

執行後,上述程式將顯示以下結果:

Current working dir : /home/tp/Python/tmp
Current working dir : /home
Closed successfully!!
python_files_io.htm
廣告