m3u filter
4 years ago in Python
import sys
import re
def printArray(a):
s = a[0]
for i in range(1, len(a)):
if i == len(a) - 1:
s += " and " + a[i]
else:
s += ", " + a[i]
print(s)
def printHelp():
print("How to use:")
print("First argument is the m3u")
print("Second argument is your channel list")
print("Ex: 'python3 m3ufilter.py ./full.m3u ./mychannels.txt'")
print("If all the files are in the same folder")
def safeOpen(path, mode):
try:
openFile = open(path, mode)
except:
sys.exit("ERROR: Could not open " + path)
return openFile
#Main
m3uFile = None;
filterFile = None;
if len(sys.argv) < 3:
printHelp()
sys.exit("ERROR: Too few arguments")
else:
m3uPath = sys.argv[1]
filterPath = sys.argv[2]
if m3uPath.endswith("m3u"):
#load m3uFile
m3uFile = safeOpen(m3uPath, "r")
else:
sys.exit("ERROR: The first file is not .m3u")
filterFile = safeOpen(filterPath, "r")
#Load channels
allChannels = []
currentChannel = ""
for line in m3uFile:
#skip to the first channel
if len(allChannels) == 0 and currentChannel == "" and not line.startswith("#EXTINF"):
continue
if line.startswith("#EXTINF") and currentChannel != "":
allChannels.append(currentChannel)
currentChannel = ""
currentChannel += line
allChannels.append(currentChannel)
m3uFile.close()
filterChannels = []
for filterChName in filterFile:
filterChannels.append(filterChName.rstrip().lower())
filterFile.close()
m3uoutFile = safeOpen('out.m3u', 'w')
matchedChannels = []
m3uoutFile.write("#EXTM3U")
for ch in allChannels:
name = re.search(r',(.*)(?=\nhttp)',ch)[1]
if name.lower() in filterChannels:
m3uoutFile.write("\n"+ch.rstrip())
matchedChannels.append(name)
m3uoutFile.close()
print("Channels found (saved in out.m3u):")
printArray(matchedChannels)