代码之家  ›  专栏  ›  技术社区  ›  CDNthe2nd

如何在每次脚本运行后创建新的json数据

  •  1
  • CDNthe2nd  · 技术社区  · 7 年前

    我在变量数据中存储了json数据。

    我想让它每次运行后都写入一个文本文件,这样我就知道哪个数据json是新的,而不是重新写入相同的json。

    目前,我正在尝试:

    Saving = firstname + ' ' + lastname+ ' - ' + email
    with open('data.json', 'a') as f:
        json.dump(Saving, f)
        f.write("\n")
    

    它只是添加到json文件和第一个代码开始的脚本的开头,我用

    Infotext = "First name : Last name : Email"
        with open('data.json', 'w') as f:
            json.dump(Infotext, f)
            f.write("\n")
    

    如何创建新文件而不是重新编写相同的json 信息文本 然后加上 储蓄 ?


    JSON输出:

    "First name : Last name : Email"
    Hello        World   - helloworld@test.com
    Hello2           World   - helloworld2@test.com
    Hello3           World   - helloworld3@test.com
    Hello4           World   - helloworld4@test.com
    

    这是我想要的输出。所以基本上它需要从

    “名字:姓氏:电子邮件”

    然后名字,姓氏邮件会在下面加起来,直到没有名字了。

    enter image description here

    现在说起来很简单-我想要的是,与其清除并添加到同一个json文件data.json,不如创建一个名为data1.json的新文件-然后如果我再次运行程序tommorow等-它将是data2.json等等。

    3 回复  |  直到 7 年前
        1
  •  1
  •   roganjosh    7 年前

    只需在文件名中使用datetime,在每次运行代码时创建一个唯一的文件。在这种情况下,粒度降低到每秒,因此,如果代码每秒运行一次以上,则将覆盖文件的现有内容。在这种情况下,请跳到名称中包含微秒的文件名。

    import datetime as dt
    import json
    
    time_script_run = dt.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
    with open('{}_data.json'.format(time_script_run), 'w') as outfile:
        json.dump(Infotext, outfile)
    

    这有多个缺点:

    1. 你会有越来越多的文件
    2. 即使加载的文件的名称中包含最新的日期时间(并且发现该文件在运行时中会增长),也只能看到上次运行之前的单个时间中的数据;很难查找完整的历史记录。

    我认为你最好使用一个轻量级的数据库,比如 sqlite3

    import sqlite3
    import random
    import time
    
    import datetime as dt
    
    # Create DB 
    with sqlite3.connect('some_database.db') as conn:
        c = conn.cursor()
    
        # Just for this example, we'll clear the whole table to make it repeatable
        try:
            c.execute("DROP TABLE user_emails")
        except sqlite3.OperationalError: # First time you run this code
            pass
    
        c.execute("""CREATE TABLE IF NOT EXISTS user_emails(
                         datetime TEXT,
                         first_name TEXT,
                         last_name TEXT,
                         email TEXT)
                  """)
    
        # Now let's create some fake user behaviour
        for x in range(5):
            now = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            c.execute("INSERT INTO user_emails VALUES (?, ?, ?, ?)", 
                      (now, 'John', 'Smith', random.randint(0, 1000)))
            time.sleep(1) # so we get new timestamps
    
    
    # Later on, doing some work
    with sqlite3.connect('some_database.db') as conn:
        c = conn.cursor()
    
        # Get whole user history
        c.execute("""SELECT * FROM user_emails 
                     WHERE first_name = ? AND last_name = ?
                     """, ('John', 'Smith'))
        print("All data")
        for row in c.fetchall():
            print(row)
        print('...............................................................')
    
        # Or, let's get the last email address
        print("Latest data")
        c.execute("""
                  SELECT * FROM user_emails 
                  WHERE first_name = ? AND last_name = ?
                  ORDER BY datetime DESC
                  LIMIT 1;
                  """, ('John', 'Smith'))
        print(c.fetchall())
    

    注意:在这段代码中,数据检索运行得非常快,因为我使用 time.sleep(1) 生成假用户数据。

        2
  •  1
  •   Barmar    7 年前

    json文件应该包含字符串列表。您应该将文件的当前内容读入变量,附加到变量,然后重写文件。

    with open("data.json", "r") as f:
        data = json.load(f)
    data.append(firstname + ' ' + lastname+ ' - ' + email)
    with open("data.json", "w") as f:
        json.dump(data, f)
    
        3
  •  0
  •   Wahalez    7 年前

    我认为您可以对文件使用seek()并在json文件的相关位置写入。例如,您需要更新firstname,在firstname之后查找:并更新其中的文本。 这里有一些例子: https://www.tutorialspoint.com/python/file_seek.htm