How can I change directory with Python pathlib

前端 未结 3 863
感情败类
感情败类 2021-02-05 02:34

What is the intended way to change directory using the Python pathlib (Documentation) functionality?

Lets assume I create a Path object as foll

3条回答
  •  不要未来只要你来
    2021-02-05 02:44

    In the Python 3.6 or above, os.chdir() can deal with Path object directly. In fact, the Path object can replace most str paths in standard libraries.

    os.chdir(path) Change the current working directory to path.

    This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file.

    New in version 3.3: Added support for specifying path as a file descriptor on some platforms.

    Changed in version 3.6: Accepts a path-like object.

    import os
    from pathlib import Path
    
    path = Path('/etc')
    os.chdir(path)
    

    This may help in the future projects which do not have to be compatible with 3.5 or below.

提交回复
热议问题