python 与pathlib库的常见操作。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 与pathlib库的常见操作。相关的知识,希望对你有一定的参考价值。

    #common path operations
    
    from pathlib import Path
    path = Path('.')

    urls = []

    for f in path.iterdir():
        with f.open('r', encoding='utf-8') as handle:
            content = handle.read()
            extracted = parser.links(content)
            urls.extend(extracted)
    print(urls)
    with open(url_file, "a") as out_file:
        out_file.write('\n'.join(urls))

\!h    p = Path('..')
    for f in p.glob('*.rst'):  # use pathlib's glob module for pattern matching
        print(f)
        
    # even recursive glob is supported:
    for f in p.glob('**/*.rst'):  # or by calling rglob() instead of glob()
        print(f)

    root = Path('/')
    subdirs = ['usr', 'local']
    usr_local = root.joinpath(*subdirs)
    # >>> /usr/local

    # Given an existing path object, it is easy to build a
    # new one with minor differences such as referring to a different file in the same directory.
    ind = Path('source/pathlib/index.rst')
    print(ind)
    # >>> source/pathlib/index.rst
    py = ind.with_name('pathlib_from_existing.py')
    print(py)
    # >>> source/pathlib/pathlib_from_existing.py
    pyc = py.with_suffix('.pyc')
    print(pyc)
    # >>> source/pathlib/pathlib_from_existing.pyc

    # create dir (and all parent dirs) if not existing
    Path(outdir).mkdir(parents=True, exist_ok=True)

    p = Path('/usr/local')
    print(p.parts)
    # >>> ('/', 'usr', 'local')  # The sequence is a tuple, reflecting the immutability of the path instance.

    p = Path('./source/pathlib/pathlib_name.py')
    print(f'path  : {p}')
    print(f'name  : {p.name}')
    print(f'stem  : {p.stem}')
    print(f'suffix: {p.suffix}')
    
    
    # joining paths, as simple as:
    p = Path("segment_one", "segment_two", "segment_three")
    "segment_one/segment_two/segment_three"
    
    # or even simpler:
\!h     pathlib.Path.home() / 'python' / 'scripts' / 'test.py'
    # gives: PosixPath('/home/gahjelle/python/scripts/test.py')
    
    # renaming file
    p.rename("new_name.rst")
    
    # reading from file
\!h     content = p.read_text()

    # pathlib supports many more things, like
    # Manipulating Directories and Symbolic Links
    # File Types & File Properties & File Permissions
    
    
\!h     Directories and files can be deleted using .rmdir() and .unlink() respectively. (Again, be careful!)
# script path
Path(__file__) 

# current working dir
Path()

# (regardless of the current working directory) you would use
from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')

# and to get the parent directory of the current working directory

from pathlib import Path
d = Path().resolve().parent

# Note that d is a Path instance, which isn't always handy.
# You can convert it to str easily when you need it:

以上是关于python 与pathlib库的常见操作。的主要内容,如果未能解决你的问题,请参考以下文章

Python文件操作都有哪些方式?

13-Python-pathlib库使用

13-Python-pathlib库使用

python 笔记:Pathlib

python pathlib模块(面向对象的文件系统路径)

python--pathlib--路径操作