from pathlib import Path
p = Path('C:/Users/Username/Documents)
It could be a file , It could be a folder , There is no guarantee that there is something in this path p = Path('C: \\', 'Users', 'Username', 'Documents')
Equivalent writing , You can take each part apart p2 = p.with_name('file2.txt')
Get other files in the same folder quickly Path object p2 = p.with_suffix('.csv')
Get the same file quickly basename But with different suffixes Path object Splicing p = Path(...) / str_of_subpath
It's very natural to connect with a division sign p = Path(...).joinpath(str_of_subpath)
You can also use the method Full path string str(p) Get the next level p.parent Folder's parent folder ; The folder where the file is located ; You can use multiple parent obtain basename, noext-basename, extp.name, p.stem, p.suffix Get the folder (os.path.dirname)p.parent that will do . If you still need to get the path of the folder str() Get the character string Tuples p.partsWindows Of C: \\
Is a separate string Whether there is , Is it a document / Folder p.exists(), p.is_file(), p.is_dir() Traverse p.iterdir() Return to generator , You can use for iteration , You need to judge whether it is a folder lookup ( Based on regularization )p.glob('*.txt')
Return to generator , You need to judge whether it is a folder , see 4 glob built-inp.glob('*/*.txt')
Find the current folder at the next lower level In all folders txtp.glob('**/*.txt')
Find the current folder Lower all levels In a folder txt Reading and writing p.read_text(...), p.read_bytes(...)