Latest web development tutorials

Python3 os.getcwd() 方法

Python3 OS 文件/目錄方法 Python3 OS文件/目錄方法


概述

os.getcwd() 方法用於返回當前工作目錄。

語法

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

os.getcwd()

參數

返回值

返回當前進程的工作目錄。

實例

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

#!/usr/bin/python3

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

Python3 OS 文件/目錄方法 Python3 OS文件/目錄方法