【发布时间】:2018-12-15 05:21:09
【问题描述】:
我有一个这样的文本文件
moviefiles.txt
['/home/share/Wallpaper/Hymnfortheweekend(remix).mp4', '/home/share/Wallpaper/mrkittengrove.mp4', '/home/share/Wallpaper/lovelyrabbitandstarycat.mp4', '/home/ share/Wallpaper/candygirl(tsar_remix).mp4', '/home/share/Wallpaper/ninelie.mp4', '/home/share/Wallpaper/allweknow.mp4', '/home/share/Wallpaper/Nanamori.mp4' , '/home/share/Wallpaper/Fragments.mp4', '/home/share/Wallpaper/alter.mp4', '/home/share/Wallpaper/memsofyou.mp4', '/home/share/Wallpaper/luvletter. mp4', '/home/share/Wallpaper/atthedge.mp4', '/home/share/Wallpaper/lifeline.mp4', '/home/share/Wallpaper/power.mp4', '/home/share/Wallpaper/ yiran.mp4', '/home/share/Wallpaper/iknewyouwereintroubl.mp4', '/home/share/Wallpaper/lookwhatyoumademedo.mp4', '/home/share/Wallpaper/continue.mp4', '/home/share/壁纸/newlife.mp4'、'/home/share/Wallpaper/alone.mp4'、'/home/share/Wallpaper/withoutyou.mp4'、'/home/share/Wallpaper/lifeline1.mp4'、'/home/分享/Wallpaper/movingon.mp4']
此文件中仅包含 1 行!
我正在尝试读取 moviefiles.txt 并将其作为列表对象,但我收到了这个奇怪的错误
Traceback (most recent call last):
File "wallpaper.py", line 8, in <module>
vdlist = eval(vdlist)
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
这是我的代码的错误部分
movfiles = open("movfiles.txt", "r")
print (movfiles.read())
vdlist=movfiles.read()
vdlist = eval(vdlist)
注意:movfiles.txt 由该文件自动生成
import glob
from tkinter.filedialog import askdirectory
folder = askdirectory()
print (folder)
mp4files=glob.glob(folder+"/*.mp4")
movfiles=glob.glob(folder+"/*.mov")
avifiles=glob.glob(folder+"/*.avi")
flvfiles=glob.glob(folder+"/*.flv")
allvideofiles=mp4files+movfiles+avifiles+flvfiles
print (mp4files)
file = open("movfiles.txt","w")
file.write(str(allvideofiles))
file.close()
有人知道如何解决这个错误吗?
【问题讨论】:
-
出于安全原因,请始终使用
ast.literal_eval而不是eval。 -
使用
eval无论如何都不是一个好方法。最好将列表作为换行符分隔的条目写入文件,然后逐行再次读取文件。 -
我在使用 ast 文件“
”时遇到这样的错误,第 0 行 ^ SyntaxError: unexpected EOF while parsing -
读取文件的内容并将其作为代码评估是吗?我也喜欢危险的生活!
标签: python string python-3.x list file