如何将文件读入lis

2024-04-16 22:58:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文本文件

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']


此文件中只包含一行!

我在努力读书电影文件.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()

有人知道如何修正这个错误吗?你知道吗


Tags: 文件txtsharehome错误folderglobfile
2条回答
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

伙计们,也许我不明白这个问题,我的代码是工作的,但转换一个列表元素中的每一行,如果你有更多的元素在同一行它不会工作。 如果是这种情况,请让我知道,我会提供一个替代解决方案

你对一个文件进行了两次读取,这意味着第二次读取将是空的。你知道吗

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()
''

Read advances the'cursorwithin the file and without any argumentsRead'尝试读取尽可能多的内容,第二次读取将继续第一次读取结束的地方,但您已经在第一次读取后的文件末尾。当然,你可以这样多次阅读:

>>> 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'

相关问题 更多 >