17.4. Pathlib Name

  • Path.name - Get the name of the file or directory

  • Path.stem - Get the name of the file without the suffix

  • Path.suffix - Get the file extension

  • Path.suffixes - Get all file extensions (for files with multiple extensions)

  • Path.parent - Get the parent directory of the path

  • Path.parts - Get all parts of the path as a tuple

  • Path.with_name(new_name) - Change the name of the file or directory

  • Path.with_suffix(new_suffix) - Change the file extension

17.4.1. SetUp

>>> from pathlib import Path
>>>
>>> myfile = Path('/home/myuser/myfile.txt')

17.4.2. Name

>>> myfile.name
'myfile.txt'

17.4.3. Stem

>>> myfile.stem
'myfile'

17.4.4. Suffix

>>> myfile.suffix
'.txt'

17.4.5. Suffixes

>>> myfile.suffixes
['.txt']

17.4.6. Parent

>>> myfile.parent
PosixPath('/home/myuser')

17.4.7. Parts

>>> myfile.parts
('/', 'home', 'myuser', 'myfile.txt')

17.4.8. With Name

>>> newfile = myfile.with_name('newfile.md')
>>> newfile
PosixPath('/home/myuser/newfile.md')

17.4.9. With Suffix

>>> newfile = myfile.with_suffix('.md')
>>> newfile
PosixPath('/home/myuser/myfile.md')