'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:
- Find a file (mp3) based on the ID you type in (in the directory specified in SongsPath.txt)
- Back it up
- 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 1:[1]
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.
Solution 2:[2]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |