用python写入m3u文件

时间:2015-12-25 13:26:53

标签: python regex scrape

我做了这个脚本我尝试写一下我用regex请求写的文件'w'只写了我尝试的最后一个条目('w''wb',{{ 1}})所有他们写下我错误的最后一个条目?

'w+'

1 个答案:

答案 0 :(得分:0)

您的数据编写代码存在一些问题:

  1. 对于找到的每个value项目,您可以循环打开文件
  2. 您只打开文件
  3. 您有意在每次迭代时将内部文件句柄位置更改为文件的开头,只读取整个文件并flush剩下的内容。这不危险,只是没必要。但是你可能需要一些时间来回顾一下你对文件操作的了解。
  4. 您使用with语句,该语句会自动关闭文件句柄,但随后会调用close()
  5. 打开文件进行写入只有在执行一次,然后循环遍历值列表时没有错误:

    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)