Python Temp

From bernie's
Jump to navigation Jump to search
import json
#from urllib import urlopen
from urllib.request import urlopen
import os
import datetime
from pathlib import Path

url = "https://www.radiomeuh.com/player/rtdata/tracks.json"
localfile = "playlist.txt"
fileId = Path(localfile)
fileId.touch(exist_ok=True)

def lastline(file):
	''' https://stackoverflow.com/questions/46258499/how-to-read-the-last-line-of-a-file-in-python '''
	with open(file, 'rb') as f:
	    try:  # catch OSError in case of a one line file 
	        f.seek(-2, os.SEEK_END)
	        while f.read(1) != b'\n':
	            f.seek(-2, os.SEEK_CUR)
	    except OSError:
	        f.seek(0)
	    return f.readline().decode()

sep = " | "
lastrecord = lastline(localfile)
date = datetime.datetime.now().strftime("%y%m%d")

with urlopen(url) as content:
	data = json.loads(content.read())
	for el in reversed(data):
		record = (f"{date}{sep}{el['time']}{sep}{el['artist']}{sep}{el['titre']}\n")
		if record is not lastrecord:
			with open(localfile, 'a') as recordlist:
				recordlist.write(record)