我做了这个脚本,我尝试在写入文件时用正则表达式编写我所请求的内容
'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()
您的数据编写代码存在一些问题:
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)