【问题标题】:Unsupported operand type(s) for +: 'WindowsPath' and 'str'+ 不支持的操作数类型:“WindowsPath”和“str”
【发布时间】:2020-05-09 06:10:57
【问题描述】:

我正在处理的代码引发错误Unsupported operand type(s) for +: 'WindowsPath' and 'str'。我已经尝试了很多东西,但都没有解决这个问题(除了删除有错误的行,但这没有帮助)。

就上下文而言,这个脚本(完成后)应该:

  1. 根据您输入的 ID(在 SongsPath.txt 中指定的目录中)查找文件 (mp3)
  2. 备份它
  3. 然后将其替换为另一个文件(重命名为上一个文件的名称)

以便获取这些文件的程序播放新歌曲而不是旧歌曲,但可以随时恢复到原始歌曲。 (歌曲从 newgrounds 下载,并通过其 newgrounds 音频门户 ID 保存)

我正在使用 Python 3.6.5

import os
import pathlib
from pathlib import Path

nspt = open ("NewSongsPath.txt", "rt")
nsp = Path (nspt.read())
spt = open("SongsPath.txt", "rt")
sp = (Path(spt.read()))
print("type the song ID:")
ID = input()
csp = str(path sp + "/" + ID + ".mp3") # this is the line throwing the error.
sr = open(csp , "rb")
sw = open(csp, "wb")
print (sr.read())

【问题讨论】:

  • Path() 不返回字符串,而是返回 Path 对象。
  • 始终共享整个错误消息。你从那个错误中理解了什么?我建议使用上下文管理器来处理文件对象。
  • path sp 是复制错误吗?应该只是sp吗?

标签: python file-handling operands


【解决方案1】:

发生的情况是您使用“+”字符连接 2 种不同类型的数据

而不是使用错误行:

csp = str(path sp + "/" + ID + ".mp3")

尝试以这种方式使用它:

csp = str(Path(sp))
fullpath = csp + "/" + ID + ".mp3"

使用 'fullpath' 变量打开文件。

【讨论】:

  • 谢谢,不知道 Path() 返回的不是字符串。
【解决方案2】:

pathlib.Path 使用除法运算符连接路径。无需转换成字符串再连接,只需使用Path对象的__div__运算符

csp = sp/(ID + ".mp3")

如果您愿意,也可以使用增强除法来更新 sp 本身。

sp /= ID + ".mp3"

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-12-06
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多