Moo*_*iss 7 python file-handling operands
我正在处理的代码抛出错误Unsupported operand type(s) for +: 'WindowsPath' and 'str'。我尝试了很多东西,但没有一个能解决这个问题(除了删除带有错误的行,但这没有帮助)。
对于上下文,此脚本(完成后)应该:
以便获取这些文件的程序播放新歌曲而不是旧歌曲,但可以随时恢复到原始歌曲。(歌曲是从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())
Run Code Online (Sandbox Code Playgroud)
Rom*_*ues 12
发生的事情是您使用“+”字符连接两种不同类型的数据
而不是使用错误行:
csp = str(path sp + "/" + ID + ".mp3")
Run Code Online (Sandbox Code Playgroud)
尝试以这种方式使用它:
csp = str(Path(sp))
fullpath = csp + "/" + ID + ".mp3"
Run Code Online (Sandbox Code Playgroud)
使用“fullpath”变量打开文件。
tde*_*ney 11
pathlib.Path使用除法运算符连接路径。无需转换为字符串然后连接,只需使用Path对象的__div__运算符
csp = sp/(ID + ".mp3")
Run Code Online (Sandbox Code Playgroud)
如果您愿意,还可以使用增广除法来更新sp自身。
sp /= ID + ".mp3"
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,您仍然拥有一个Path可以在脚本的其余部分中继续使用的对象。您的脚本没有理由将其转换为字符串。您可以Path在 open 调用中使用该对象,或者更好的是,使用对象open上的方法Path。
csp = sp / (ID + ".mp3")
sr = csp.open("rb")
sw = csp.open("wb")
Run Code Online (Sandbox Code Playgroud)