Search code examples
pythonfilereadlinepytube

Python: How do you take a random word (if the word itself is also random) out of a file?


My first question so I'll simplify it. So I have a txt file that breaks down audio files:

 <Stream: itag="249"; mime_type="audio/webm" abr="50kbps" acodec="opus" progressive="False" type="audio">
 <Stream: itag="250"; mime_type="audio/webm" abr="70kbps" acodec="opus" progressive="False" type="audio">
 <Stream: itag="251"; mime_type="audio/webm" abr="160kbps" acodec="opus" progressive="False" type="audio">

I wanted to take all itag="{n}"; out and print them. My preferred output is:

itag="249"
itag="250"
itag="251"

But the thing is, {n} will be different for the 3 itags everytime the user provides different audio. Here's the code I tried:

with open(report_file) as file_obj:
    for line in file_obj:
        disk_read=''.join(map(str, open(report_file).readline()))
        index=disk_read.find(';')
        return disk_read[:index]+disk_read[disk_read.find('\n'):]

But the output is:

 <Stream: itag="249"

and the rest just disappeared. Any help would be very appreciated! EDIT: Thank you not_speshal! Case closed, thank you everyone


Solution

  • Try this:

    def parse(report_file):
        itags = list()
        with open(report_file) as file_obj:
            for line in file_obj:
                itags.append(line.split(";")[0].split(":")[-1].strip())
        return itags
    
    >>> parse("test.txt")
    ['itag="249"', 'itag="250"', 'itag="251"']