将os.path转换为pathlib模块,但无法正常工作

问题描述 投票:1回答:1

我一直在尝试用新的pathlib模块替换os.path。在这些行中,os.path每次都正常运行,而没有错误,而Pathlib模块带来了错误:

Path' and 'str'
[!] send_logs // Error.. ~ unsupported operand type(s) for +: 'PosixPath' and 'str'

主要目的是将文件写入该文件夹;使用Path.is_dir(log_dir)返回True。通过pathlib模块尝试执行此操作会导致错误。香港专业教育学院试图找到其他来源的答案,并来到PosixPath作为在expanduser中使用的单独变量。无济于事,我被带到这里

不好意思,因为我是新手,这是我的第一个“项目”!非常感谢所有帮助。我也遇到过类似的问题,但它们直接用于查找主目录,即Path.owner(Path.home())

#log_dir = os.path.expanduser('~') + '/Downloads/'   --- commented out for pathlib/path
p = PosixPath('~' + '/Downloads/')
log_dir = Path.expanduser(Path(p))

感谢您提供的帮助。设法使它与单行一起工作:与os.path.expanduser()

相同
log_dir = str(PosixPath('~' + '/Downloads/').expanduser())
python-3.x path operating-system os.path pathlib
1个回答
0
投票

编辑:我认为您正在寻找这个:

>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

请记住,pathlib.Path(somepath)返回一个pathlib对象,但不返回字符串。要将pathlib对象连接为字符串,请使用

str(pathlib.Path(somepath))+"somepath"

或在pathlib文档中寻找.str或类似方法

© www.soinside.com 2019 - 2024. All rights reserved.