【问题标题】:Python - replace vs update filePython - 替换vs更新文件
【发布时间】:2016-11-11 17:41:44
【问题描述】:

我根据播放列表的大小将播放列表上传到目录中。

首先我将以下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 上传到空目录的方式。

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

编辑

这是在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
  • 我该如何解决这个问题?
  • 语句db = playlist2db = playslist1 后面跟着相同的db = json.load(f):为什么要覆盖变量?
  • 错误。关心修复代码和答案?
  • 我提供了答案。我还注意到一个变量 playlist_short 之前没有被引用,所以我认为它与这个示例的 playlist1 相同。

标签: python file dictionary


【解决方案1】:

在我看来db 变量被错误地覆盖,因此总是从db/user1.json 加载数据。 快速 修复方法是注释掉两个分支中的db = json.load(f) 语句:毕竟,您想要完全重写文件内容。

虽然我也会将这两个代码块实现为函数,因为它们重复相同的确切逻辑,这使其更具可读性和更易于调试:

import os
import json

playlist1 = {'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}}
playlist2 = {'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}}


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


def update_and_save_playlist(playlist, filepath):
    with open(filepath, 'r+') as f:
        db = playlist
        # increment track count
        updateTrackCounts(db, value=1.0)
        # update json here
        f.seek(0)
        f.truncate()
        json.dump(db, f)
        print (db)


def save_playlist(playlist, filepath):
    with open(filepath, 'w') as f:
        json.dump(playlist, f)


if os.path.exists('db/user1.json'):
    if len(playlist1['user1'].values()) < 3:
        # save playlist 2
        update_and_save_playlist(playlist2, 'db/user1.json')
    else:
        # save playlist 1
        update_and_save_playlist(playlist1, 'db/user1.json')
else:
    if len(playlist1['user1'].values()) < 3:
        save_playlist(playlist2, 'db/user1.json')
    else:
        save_playlist(playlist1, 'db/user1.json')

编辑 合并这两个播放列表 pre/pos 看起来更像是一个问题。为此,updateTrackCounts 需要调整。由于new 播放列表将包含比old 更多的数据,一种方法是提供updateTrackCounts 两个播放列表,并根据曲目就地更新新的播放列表存在于旧版本中:

def updateTrackCounts(new_dict, old_dict, value=0):
    # new_dict will have the same or more data than old_dict
    for user, new_tracks in new_dict.items():
        # check if this user, and the tracks were in the old dict
        if user in old_dict:
            for old_track in old_dict[user]:
                if old_track in new_tracks:
                    new_dict[user][old_track] += value

例如关于用法,调用后:

updateTrackCounts(playlist_pos, playlist_pre, value=1.0)

playlist_pos 将与joined_playlist 相同

这可能需要根据您的目标进行调整:例如,这没有考虑新旧相同的情况,因为没有发生任何变化。

【讨论】:

  • 我得到了带有增量值的新播放列表,但增量值仅对之前存在的曲目有意义。我发布了一个编辑以澄清所需的输出:默认值 = 1.0 的新轨道和递增值的重复轨道。你还能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2022-01-17
  • 1970-01-01
  • 2013-03-18
  • 2013-06-26
  • 2011-08-25
  • 2022-01-16
相关资源
最近更新 更多