[英]How can i add more json data to a text file in python?
Hi sorry this seems to be a very bad question but whenever i create a json txt file in python and write to it, it only saves temporarily.嗨,抱歉,这似乎是一个非常糟糕的问题,但是每当我在 python 中创建一个 json txt 文件并写入它时,它只会暂时保存。 For example, i have a for loop to write text to the file over the amount of times the user wants it to.例如,我有一个 for 循环,可以在用户希望的次数内将文本写入文件。 I know it does it multiple times because i have a counting function to print each time it does it, but the text file that is being written to only saves one loop.我知道它会执行多次,因为每次执行时我都有一个计数功能可以打印,但是正在写入的文本文件仅保存一个循环。 So say i want to print the numbers of every time i do the loop, i may ask it to run 4 times, the numbers that should be printed are 0, 1, 2, 3, the only number i see printed to the file at the end is 3 as i keep writing over my data.所以说我想打印每次循环时的数字,我可能会要求它运行 4 次,应该打印的数字是 0、1、2、3,我看到打印到文件的唯一数字是最后是 3,因为我一直在写我的数据。 Here is my code so someone can assist me and like always any and all help is greatly appreciated.这是我的代码,因此有人可以帮助我,并且非常感谢任何和所有帮助。
def create_tasks():
num_tasks = int(num_tasks_entry.get())
global size
num = 0
for num in range(0, num_tasks):
data = {}
data['task'] = []
data['task'].append({
'profile': profiles_select.get(),
'task_id': num,
'product_link': productlink_entry.get(),
'delay': int(delay_entry.get()),
})
num = num + 1
with open('tasks.txt', 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, indent=2)
Another example, in my code i want the out put file to be this information printed the amount of times the user selects.另一个例子,在我的代码中,我希望输出文件是打印用户选择次数的信息。
You could write your function like this:你可以这样写你的函数:
def create_tasks():
num_tasks = int(num_tasks_entry.get())
global size
data = {}
data['task'] = []
for num in range(0, num_tasks):
data['task'].append({
'profile': profiles_select.get(),
'task_id': num,
'product_link': productlink_entry.get(),
'delay': int(delay_entry.get()),
})
with open('tasks.txt', 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, indent=2)
Also, why are you incrementing num
inside the for loop?另外,为什么要在 for 循环内增加num
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.