The following code:
from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Desktop + "/subdir"
gets the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-eb31bbeb869b> in <module>()
1 from pathlib import Path
2 Desktop = Path('Desktop')
----> 3 SubDeskTop = Desktop+"/subdir"
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
I'm clearly doing something shady here, but it raises the question: How do I access a subdirectory of a Path
object?
The sys. path. append() is a built-in function of the sys module in Python that can be used with path variables to add a specific path for an interpreter to search.
os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.
pathlib
object is /
from pathlib import Path
Desktop = Path('Desktop')
# print(Desktop)
WindowsPath('Desktop')
# extend the path to include subdir
SubDeskTop = Desktop / "subdir"
# print(SubDeskTop)
WindowsPath('Desktop/subdir')
# passing an absolute path has different behavior
SubDeskTop = Path('Desktop') / '/subdir'
# print(SubDeskTop)
WindowsPath('/subdir')
os.path.join()
’s behavior):>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
Path('/subdir')
.Resources:
What you're looking for is:
from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Path.joinpath(Desktop, "subdir")
the joinpath()
function will append the second parameter to the first and add the '/' for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With