如何在Python中将字符串附加到路径? [英] How do I append a string to a Path in Python?

查看:69
本文介绍了如何在Python中将字符串附加到路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Desktop + "/subdir"

出现以下错误:

    ---------------------------------------------------------------------------
 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'

我在这里显然在做一些可疑的事情,但这引发了一个问题:如何访问Path对象的子目录?

I'm clearly doing something shady here, but it raises the question: How do I access a subdirectory of a Path object?

推荐答案

结果很简单.正确的运算符是'/'

Turns out the answer was embarrassingly simple. The correct operator is '/'

from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Desktop / "subdir"

这篇关于如何在Python中将字符串附加到路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆