问题
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?
回答1:
Turns out the answer was embarrassingly simple. The correct operator is '/'
from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Desktop / "subdir"
回答2:
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.
回答3:
Or
from pathlib import Path
p1 = Path('somewhere')
p2 = p1.joinpath(p1, "over/there")
# or if you want to just create it in one line
p1.joinpath(p1, "new/place").mkdir()
来源:https://stackoverflow.com/questions/48190959/how-do-i-append-a-string-to-a-path-in-python