如何解决在 dict 错误中打开字符串 - 行继续符后的意外字符 - python
问题:
我正在尝试将字符串转换为字典,因此我可以尝试将其与我的其他字典合并。但是,当我尝试使用 eval() 命令时,它给出了一个错误 unexpected character after line continuation character (<string>,line 1)
目标:
我的目标是将我的 mp4 路径添加到我的元数据字典中,这样我就可以一次性将数据插入到 sqlite 中。
import os
import subprocess
##from tinytag import TinyTag #that is to pull Metadata from my mp4s
def playmusic(name):
count = 0
extf = ['$RECYCLE.BIN','System Volume information']
for root,dirs,files in os.walk(r'\\Vgmstation\\e\\',followlinks=True):
dirs[:] = [d for d in dirs if d not in extf]
for file in files:
if name in file and file.endswith(".mp4"):
vlc='C:/Program Files/VideoLAN/VLC/vlc.exe'
music=str(os.path.join(file))
musicpath=str("{"+'path: '+'+(os.path.join(root,file)+'+'}'))
musicpath_dict = eval(musicpath)
## tm = TinyTag.get(musicpath)
## tmd = tm.duration
musiconly= os.path.splitext(music)[0]
print(musicpath)
count = count + 1
if count == 5:
break
if count >= 5:
break
print("Finish")
input()
try:
s=raw_input("name: ")
playmusic(s)
except Exception as e:
print(e)
print("Error")
这是上面运行的代码的结果:
name: m
{path: \\Vgmstation\\e\\Dreamcast\Dead or Alive 2\27 UnkNown.mp4}
{path: \\Vgmstation\\e\\Dreamcast\Dead or Alive 2\28 UnkNown.mp4}
{path: \\Vgmstation\\e\\Dreamcast\Dead or Alive 2\Blazed Up Melpomene.mp4}
{path: \\Vgmstation\\e\\Dreamcast\Dead or Alive 2\Bomb Factory - Exciter.mp4}
{path: \\Vgmstation\\e\\Dreamcast\Dead or Alive 2\Bomb Factory - Exciter2.mp4}
Finish
这是我尝试将路径转换为字典的代码:
##code from above
musicpath_dict = eval(musicpath)
#code from above
如果我打印 musicpath_dict
,结果如下:
name: m
unexpected character after line continuation character (<string>,line 1)
Error
我相信问题是我在字符串中的斜线,但我需要那些原样的斜线。目标是在我的 sqlite 数据库中添加一个路径行,这样我就可以拉出文件的位置,以便稍后在路上播放这首歌。 (如果这是有道理的)
如果有人有任何建议或想法,请告诉我。
感谢您的时间,
解决方法
永远不要使用 eval
创建变量。它可能会导致错误并且完全没有必要。直接创建字典就可以得到你想要的:
musicpath_dict = {'path': os.path.join(root,file)}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。