Home > database >  How to add texts in a file as an input to a dictionary
How to add texts in a file as an input to a dictionary

Time:11-10

I created a script to read info in an m3u8 file and store them in a dictionary.

First part of the code is working, but the while loop doesn't seem to be running at all. And it doesn't even give out error.Probably it cannot be a syntax error. I can't imagine what could be the cause..

file=open("Downloads/chunk.m3u8", "r")
f = file.readlines()
infodict={}
x=0
x2=0
y=["#EXTENC","#PLAYLIST","#EXTGRP","#EXTLAP","#EXTART","#EXTGENRE","#EXTM3A","#EXTBYT","#EXTBIN","#EXTIMG","#EXT-X-VERSION","#EXT-X-START","#EXT-X-PLAYLIST-TYPE","#EXT-X-TARGETDURATION","#EXT-X-MEDIA-SEQUENCE","#EXT-X-INDEPENDENT-SEGMENTS","#EXT-X-MEDIA","#EXT-X-STREAM-INF","#EXT-X-BYTERANGE","#EXT-X-DISCONTINUITY","EXT-X-DISCONTINUITY-SEQUENCE","#EXT-X-KEY","#EXT-X-MAP","#EXT-X-PROGRAM-DATE-TIME","#EXT-X-DATERANGE","#EXT-X-I-FRAMES-ONLY","#EXT-X-I-FRAME-STREAM-INF","#EXT-X-SESSION-DATA","#EXT-X-SESSION-KEY"]
y1=y[x2]
if "#EXTM3U" in f[x]:
        s="#EXTM3U"
        infodict[s]= ""
        x=x 1
while x2<=len(y):
      if y1 in f[x]:
        s=f[x].rstrip("\n").split(":",1)
        infodict[s[x] ":"]= s[x 1]
        x=x 1
        x2=x2 1
      elif "#EXT-X-ENDLIST" in f[x]:
           break
      else:
        x2=x2 1    
        continue
       
print(infodict)

Only the output is this,

{'#EXTM3U': ''}

CodePudding user response:

In your loop, if y1 is not in f[x] then x2 will increment until x2 is equal to the length of y. The key problem here is that x (and therefore f[x]) and y1 never change in this condition and so will always evaluate the same way. That produces the behavior of the while loop executing without doing anything, all it is doing is hitting the "else" condition over and over until the loop terminates.

Another bit of advice that I think would help you reason about this code is to avoid opaque variable names like x1, x2, y1, y2, and so on. Your variable names should be names - that is, they should convey some meaning to the reader which will help the reader (even if that reader is only you) understand what the code is doing. It's better to type a few more characters and have a clear description than to save a few keystrokes and not understand what the code is doing.

  • Related