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:
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())
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.
pathlib.Path joins paths using the division operator. No need to convert to a string and then concatenate, just use the Path object's __div__ operator
csp = sp/(ID + ".mp3")
You could also use augmented division to update sp itself, if you prefer.
sp /= ID + ".mp3"
In both cases, you still have a Path object which you can keep using through the rest of the script. There is no reason for your script to convert it to a string. You can either use the Path object in the open call, or better, use the open method on the Path object.
csp = sp / (ID + ".mp3")
sr = csp.open("rb")
sw = csp.open("wb")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With