我完成了这个脚本--我尝试用regex编写我请求的内容--当涉及到写入一个文件时,'w'只写最后一个条目--我尝试过('w'、'wb'、'w+') --所有这些条目都写在我做错的地方?
#-*- coding: utf-8 -*-
import urllib2,urllib
import re
import os
import sys
value=[]
url='https://www.youtube.com/feeds/videos.xmlchannel_id=UCHXdylbsyDVN4UO2Fv8Cgm&API'
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML,like Gecko) Version/7.0.3 Safari/573.75.14')
response = urllib2.urlopen(req)
link=response.read()
response.close()
match=re.compile('<entry>\n <id>.+?</id>\n <yt:videoId>(.+?)</yt:videoId>\n <yt:channelId>.+?</yt:channelId>\n <title>(.*?)\(HD\)</title>').findall(link)
for videoid,isim in match:
#print videoid,isim
name='#EXTINF:-1 ,'+isim+'\n'
link='plugin://plugin.video.youtube/play/?video_id='+videoid+'\n'
value.append((str(name), str(link)))
for name,link in value:
#print name,link
with open('C:\\Users\\dir\\Desktop\\muhtesem_yuzyil_kosem.m3u', 'wb+') as f:
f.write(name)
f.write(link)
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
f.flush()
f.close()发布于 2015-12-25 13:56:10
您的数据编写代码很少有问题:
value项打开flush剩下的内容。这并不危险,只是没有必要。但是您可以花一些时间回顾一下您对文件操作的了解。with语句,它会自动关闭文件句柄,但是仍然会调用close()仅当您只编写一次文件,然后循环遍历您的值列表时,打开文件并没有什么问题:
with open('C:\\Users\\dir\\Desktop\\muhtesem_yuzyil_kosem.m3u', 'wb') as f:
for name,link in value:
f.write(name)
f.write(link)或者,您可以在每次迭代中打开文件,但要确保打开文件用于读取和写入:
for name,link in value:
with open('C:\\Users\\dir\\Desktop\\muhtesem_yuzyil_kosem.m3u', 'r+b') as f:
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
# make sure that data is written only after cursor was positioned after current file content
f.write(name)
f.write(link)https://stackoverflow.com/questions/34463265
复制相似问题