首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python写入m3u文件

用python写入m3u文件
EN

Stack Overflow用户
提问于 2015-12-25 13:26:52
回答 1查看 2.8K关注 0票数 0

我完成了这个脚本--我尝试用regex编写我请求的内容--当涉及到写入一个文件时,'w'只写最后一个条目--我尝试过('w''wb''w+') --所有这些条目都写在我做错的地方?

代码语言:javascript
复制
#-*- 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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-25 13:56:10

您的数据编写代码很少有问题:

  1. 在循环中打开文件,为找到的每个value项打开
  2. 您只为编写文件打开文件
  3. 在每次迭代时,您都会故意将内部文件句柄位置更改为文件的开头,只需读取整个文件和flush剩下的内容。这并不危险,只是没有必要。但是您可以花一些时间回顾一下您对文件操作的了解。
  4. 您使用with语句,它会自动关闭文件句柄,但是仍然会调用close()

仅当您只编写一次文件,然后循环遍历您的值列表时,打开文件并没有什么问题:

代码语言:javascript
复制
with open('C:\\Users\\dir\\Desktop\\muhtesem_yuzyil_kosem.m3u', 'wb') as f:
       for name,link in value:
            f.write(name)
            f.write(link)

或者,您可以在每次迭代中打开文件,但要确保打开文件用于读取和写入:

代码语言:javascript
复制
 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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34463265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档