How do I append a string to a Path in Python?

放肆的年华 提交于 2020-05-12 11:42:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!