pythonfile-handlingoperands

Unsupported operand type(s) for +: 'WindowsPath' and 'str'


The code I'm working on throws the error Unsupported operand type(s) for +: 'WindowsPath' and 'str'. I have tried many things, and none have fixed this (aside from removing the line with the error, but that's not helpful).

For context, this script (when it's done) is supposed to:

  1. Find a file (mp3) based on the ID you type in (in the directory specified in SongsPath.txt)
  2. Back it up
  3. Then replace it with another file (renamed to the previous file's name)

so that the program that fetches these files plays the new song instead of the old one, but can be restored to the original song at any time. (the songs are downloaded from newgrounds and saved by their newgrounds audio portal ID)

I'm using 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())

Solution

  • What is happening is that you are using the "+" character to concatenate 2 different types of data

    Instead of using the error line:

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

    Try to use it this way:

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

    Use the 'fullpath' variable to open file.