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

2024-04-18 22:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

变量数据中存储了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,而是用Infotext信息创建新文件,然后加上保存?你知道吗


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文件数据.json,我希望它创建一个名为data1.json的新文件-然后如果我再次运行程序tommorow等等-它将是data2.json等等。你知道吗


Tags: 文件数据nametestcomjsonworlddata
3条回答

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)

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

只要在文件名中使用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)生成假用户数据,所以只需要~5秒就可以运行。你知道吗

相关问题 更多 >