Search code examples
pythonpython-3.xpathlib

Python 3.10.10 extracting filename from fullpath, not working with Path


Using Python 3.10.10 I want to extract file name from fullpath, using Path from pathlib module.

From below code, I expect to get test.pdf name, but this code prints full pathname

from pathlib import Path
Path(r"C:\Users\work\test.pdf").name

'C:\Users\work\test.pdf'

May I know why it's not giving the filename from above path? How to get the file from full path name?

Thanks


Solution

  • The Path() function parses filenames according to the current operating system. If you're on Unix and want to process Windows paths, you need to use the PureWindowsPath subclass directly.

    >>> from pathlib import PureWindowsPath
    >>> PureWindowsPath(r"C:\Users\work\test.pdf").name
    'test.pdf'