1

我有一个像这样的文本文件

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/Wallpaper/newlife.mp4'、'/home/share/Wallpaper/alone.mp4'、'/home/share/Wallpaper/withoutyou.mp4' , '/home/share/Wallpaper/lifeline1.mp4', '/home/share/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()

任何人都知道如何解决这个错误?

4

2 回答 2

3

您正在从文件中读取两次,这意味着第二次读取将是空的。

movfiles = open("movfiles.txt", "r")
print (movfiles.read())
vdlist=movfiles.read() # this is empty.

你应该使用

vdlist=movfiles.read()
print vdlist

反而。

>>> f = open("hi.txt")
>>> f.read()
'hi\n'
>>> f.read()
''

读取推进“光标读取”within the file and without any arguments尝试尽可能多地读取,第二次读取将在第一次读取结束的地方继续,但在第一次读取后您已经位于文件的末尾。您当然可以像这样进行多次读取:

>>> f = open("hi.txt")
>>> f.read(1)
'h'
>>> f.read()
'i\n'

在这种情况下,第一次读取只会将“光标”推进一个字节,因此第二次读取仍会返回一些数据。

您还可以使用 seek 更改光标的位置,这意味着您可以返回文件的开头并再次阅读:

>>> f = open("hi.txt")
>>> f.read()
'hi\n'
>>> f.seek(0)
>>> f.read()
'hi\n'
于 2018-07-06T15:06:15.123 回答
1
movfiles = open("movfiles.txt", "r")#open the file in reading mode
a= (movfiles.readlines())#read all the lines and save in a list where each line is an element
print (a)#print your list

伙计们,也许我想念这个问题,我的代码正在工作,但是转换列表元素中的每一行,如果同一行中有更多元素,它将无法工作。如果是这种情况,请告诉我,我将提供替代解决方案

于 2018-07-06T15:05:02.730 回答