简体   繁体   English

Python pathlib无法使用/构建路径

[英]Python pathlib cannot build path with /

I am using the library pathlib , and try to build a Path in the following way. 我正在使用库pathlib ,并尝试通过以下方式构建路径。

BASE_DIR = Path(__file__).ancestor(3)
secrets_file = BASE_DIR / 'main_app' / 'settings' / 'secrets.json'

However, when running this, I get the following error: 但是,运行此命令时,出现以下错误:

TypeError: unsupported operand type(s) for /: 'Path' and 'str'

I think I am following the syntax as defined in the pathlib documentation (but probably I am not in an obscure way). 我想我遵循的是pathlib 文档中定义的语法(但可能我不是很晦涩)。

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'

What am I doing wrong? 我究竟做错了什么?

Almost certainly, you have defined a custom class called Path (or imported Path from another module). 几乎可以肯定,您已经定义了一个称为Path的自定义类(或从另一个模块导入的Path)。 In either case, that Path overshadows the one from pathlib. 无论哪种情况,该路径都会使pathlib的路径蒙上阴影。 To verify, run 要验证,请运行

print(Path.__module__)

to find out which module Path is coming from. 找出Path来自哪个模块。

For readability I prefer using Path.joinpath . 为了便于阅读,我更喜欢使用Path.joinpath In your case, it will be : 在您的情况下,它将是:

BASE_DIR.joinpath('main_app','settings', 'secrets.json')

Thus you can use * operator and for long lines it will be more comfortable. 因此,您可以使用*运算符,并且对于较长的行会更舒适。 Using the tools the library provided you ensures you won't run into these errors, since they handle the details for you. 使用该库提供的工具,可以确保您不会遇到这些错误,因为它们会为您处理详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM