python - + : 'WindowsPath' and 'str' 不支持的操作数类型

标签 python file-handling operands

我正在处理的代码抛出错误 Unsupported operand type(s) for +: 'WindowsPath' and 'str' .我尝试了很多东西,但没有一个能解决这个问题(除了删除带有错误的行,但这没有帮助)。
对于上下文,此脚本(完成后)应该:

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

  • 以便获取这些文件的程序播放新歌曲而不是旧歌曲,但可以随时恢复到原始歌曲。 (歌曲是从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())
    

    最佳答案

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

    而不是使用错误行:

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

    尝试以这种方式使用它:
    csp = str(Path(sp))
    fullpath = csp + "/" + ID + ".mp3"
    

    使用“fullpath”变量打开文件。

    关于python - + : 'WindowsPath' and 'str' 不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870637/

    相关文章:

    bash 错误 : syntax error: operand expected (error token is ")

    python - 如何使用对数损失度量将 sgdclassifier 铰链损失与 Gridsearchcv 一起使用?

    c++ - 在应用程序之间共享数据——共享内存与 D-Bus 与文件操作

    python - 如何用印地语将数据写入文件?

    c++ - 在简单的文件处理程序中获得异常输出

    operators - 二元关系运算符中左右操作数的学术名称是什么?

    java - 如何将两个操作数和一个运算符合并到一个表达式中以获得最终答案?

    python - Pandas 'concat/upsert' 数据帧

    python - 3.5 : Type Hinting and Method Overloading

    python - 如何显示另一个线程拥有的文件?