Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thay đổi và lấy thư mục làm việc hiện tại trong Python (os.chdir, os.getcwd)

Module os quản lý current working directory (CWD).

Lấy CWD

import os
print(os.getcwd())  # /home/user/project

Thay đổi CWD

os.chdir('my_folder')        # relative path
os.chdir('/absolute/path')   # absolute path
os.chdir('..')               # thư mục cha

Context manager (Python 3.11+: contextlib.chdir)

from contextlib import chdir
import os

print(os.getcwd())  # /home/user
with chdir('/tmp'):
    print(os.getcwd())  # /tmp
print(os.getcwd())  # /home/user (khôi phục tự động)

Python < 3.11: tự viết context manager

from contextlib import contextmanager

@contextmanager
def pushd(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old)

with pushd('/tmp'):
    print(os.getcwd())