我已经根据播放列表的大小将播放列表上传到目录中。Python - 替换vs更新文件
首先我上传以下dict
到一个空目录:
playlist_pre = {'user1': {u'Codex': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Videotape': 1.0, u'Pyramid Song': 1.0}}
那么,这一个:
playlist_pos = {'user1': {u'With Or Without You - Jo Whiley Show - BBC Live Session': 1.0, u'Codex': 1.0, u'Daydreaming': 1.0, u'The Man Who Sold The World - 2015 Remastered Version': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Sparks': 1.0, u'Videotape': 1.0, u'Asleep - 2011 Remastered Version': 1.0, u'Pyramid Song': 1.0, u'Nude': 1.0}}
我这是怎么上传播放列表目录,连连:
if os.path.exists('db/user1.json'):
if len(playlist_pos['user1'].values()) < 3:
with open('db/user1.json', 'r+') as f:
db = playlist_pos
db = json.load(f)
# increment track count
updateTrackCounts(db,value=1.0)
#update json here
f.seek(0)
f.truncate()
json.dump(db, f)
print (db)
else:
with open('db/user1.json', 'r+') as f:
db = playlist_pos
db = json.load(f)
# increment track count
updateTrackCounts(db,value=1.0)
#update json here
f.seek(0)
f.truncate()
json.dump(db, f)
print (db)
这是我如何将第一个,playlist_pre
上传到空的di教区长。
else:
if len(playlist_pre['user1'].values()) < 3:
with open('db/user1.json', 'w') as f:
json.dump(playlist_pre, f)
else:
with open('db/user1.json', 'w') as f:
json.dump(playlist_pre, f)
PS:function
被称为:
def updateTrackCounts(d, value=0):
for i in d:
if isinstance(d[i], dict):
updateTrackCounts(d[i], value)
elif isinstance(d[i], float):
d[i] += value
EDIT
这是所需的输出时playlist_pos
之后产生playlist_pre
:一个新的文件接合之前和之后的播放列表;
重复曲目有incremented value
,和新的轨道有default value = 1.0
joined_playlist = {'user1':
{u'Codex': 2.0, u'High And Dry': 2.0, u'Hey': 2.0, u'O': 2.0, u'Videotape': 2.0, u'Pyramid Song': 2.0, u'With Or Without You - Jo Whiley Show - BBC Live Session': 1.0, u'Daydreaming': 1.0, u'The Man Who Sold The World - 2015 Remastered Version': 1.0, u'O': 1.0, u'Sparks': 1.0, u'Asleep - 2011 Remastered Version': 1.0, u'Nude': 1.0}}
在我看来,你总是加载'db = json.load(f)',并且总是指向'user1.json'。 – sal
我该如何解决这个问题? –
语句'db = playlist2'和'db = playslist1'后面跟着相同的'db = json.load(f)':你为什么覆盖变量? – sal