试着编写一个每天都创建一个新的json文件的python代码

时间:2018-06-19 03:04:22

标签: python json python-3.x

我正在研究人脸识别模型的json日志,我的任务是编写一个每天动态创建新文件的代码。我有一个代码,但不确定为什么它只写第一个日志。只要我的相机继续识别脸部,我希望它能够连续追加。

这是我的代码:

from datetime import datetime,timedelta
import os
from pprint import pprint
import json

yesterday = datetime.now() - timedelta(days=1)
yesterday1 = datetime.strftime(yesterday, '%Y%m%d')
yesterday_str = str(yesterday1)
now1 = datetime.strftime(datetime.now(), '%Y%m%d')
now1_str = str(now1)

def write_logs(time,date,name,accuracy,direction):
    entry = {'time':time,'name':name,'accuracy':accuracy,'direction':direction}
    yesterday_log_file = './log'+yesterday_str+'.json'
    log_file = './log'+now1_str+'.json'

    if os.path.exists(yesterday_log_file):
        with open(yesterday_log_file) as f:
            Date = json.load(f)
            Date1 = (Date[-1])
            Comparision_Date = Date1['time']
            a = datetime.strptime(Comparision_Date[:10],'%d/%m/%Y')
            print(a)
            now = datetime.strptime(datetime.now(),'%d/%m/%Y')
        if a == now:
            with open(yesterday_log_file, 'r') as r:
                data = json.load(r)
        data.append(entry)
        with open(log_file, mode='w') as f:
            json.dump(data, f, indent=3)    
        if a < now:
            # Create file with JSON enclosures
            with open(log_file, mode='w') as f:
                json.dump([], f)

        # The file already exists, load and update it
        with open(log_file, 'r') as r:
            data = json.load(r)

        data.append(entry)

        # Write out updated data
        with open(log_file, mode='w') as f:
            json.dump(data, f, indent=3)

    else:
        # Create file with JSON enclosures
        with open(log_file, mode='w') as f:
            json.dump([], f)

    # The file already exists, load and update it
    with open(log_file, 'r') as r:
        data = json.load(r)

    data.append(entry)

    # Write out updated data
    with open(log_file, mode='w') as f:
        json.dump(data, f, indent=3)


        return [entry]

但是,让我告诉你,它适用于@ T.Ray在这里提到的单个if语句:While trying to append Python dict to JSON it writes only once

2 个答案:

答案 0 :(得分:1)

将您的mode='w'更改为mode='a'

  • w会覆盖任何现有文件
  • a只是简单地附加在现有文件上(如果不存在,则创建一个)

这里有很多好消息: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

答案 1 :(得分:0)

如果您打算每天在午夜创建一个新的日志文件,则无需比较日期。如果是午夜,那么新日期将始终大于旧日期(即昨天)。因此,比较似乎没有任何意义。如果是新的一天,write_logs将自动创建一个新的日志文件。现在,如果需要创建一个新的日志文件(在午夜),无论是否有要写入的条目,那么都可以编写一个包装函数来处理该问题:

def update_logs(args=None):

    # If no entry is passed, create new log file
    if not args:

        log_file = './log'+now_str+'.json'

        if not os.path.exists(log_file):
            # Create file with JSON enclosures
            with open(log_file, 'w') as f:
                json.dump([], f)

    else:
        # A new entry is passed, update existing log file
        write_logs(*args)


def write_logs(time, date, name, accuracy, direction):

    entry = {'time': time,
             'name': name,
             'accuracy': accuracy,
             'direction': direction}

    log_file = './log'+now_str+'.json'

    if not os.path.exists(log_file):
        # Create file with JSON enclosures
        with open(log_file, 'w') as f:
            json.dump([], f)

    # The file already exists, load and update it
    with open(log_file, 'r') as r:
        data = json.load(r)

    data.append(entry)

    # Write out updated data
    with open(log_file, 'w') as f:
        json.dump(data, f, indent=3)

    return [entry]

# Example records
entries = [("18/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
           ("18/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
           ("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
           ("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
           ("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default'),
           ("13/06/2018 - 20:39:07", 'whatever', "Rajkiran", "97.22941", 'default')]


# Case 1: Log file already exists, update it
now = datetime.strftime(datetime.now(), '%Y%m%d')
now_str = str(now)

for entry in entries:
    update_logs(entry)

# Case 2: Midnight, no entries, create a new empty log file
now = datetime.strftime(datetime.now() + timedelta(days=1), '%Y%m%d')
now_str = str(now)

update_logs()

# Case 3: Midnight, with entries to write
now = datetime.strftime(datetime.now() + timedelta(days=1), '%Y%m%d')
now_str = str(now)

for entry in entries:
    update_logs(entry)

致电update_logs将为您处理所有事情。