gpt4 book ai didi

python - 如何显示所有数据并将其保存在文本文件中?

转载 作者:行者123 更新时间:2023-12-01 01:37:10 25 4
gpt4 key购买 nike

read = db.Student.find()
# use iter() to include loop for the first item index = 0
# use next(read, None) if you want to skip the first item index = 0
# object = iter(read)
object = iter(read)
'''Do a for loop to loop and print out each document'''
for object in read:
with open("Student.txt", "w", newline="") as fp:
read_records = str(object['_id']), str(object['ID']), object['item'],
str(object['qty'])
r = ' '.join(read_records)
print(r)
fp.write(r)
fp.close()

首先,我想从集合中检索所有数据。其次,我想将所有检索到的数据保存到文本文件中。但是,我只能设法保存最后一个元素的数据。我无法将文本文件中的第一个元素保存到第四个元素!请帮忙!

最佳答案

您将重新打开输出文件以在循环的每次迭代中进行写入。每次迭代都会以写入模式打开一个新文件,覆盖现有的“Students.txt”。

read = db.Student.find()
# use iter() to include loop for the first item index = 0
# use next(read, None) if you want to skip the first item index = 0
# object = iter(read)
object = iter(read)
'''Do a for loop to loop and print out each document'''
with open("Student.txt", "w", newline="") as fp:
for object in read:
read_records = str(object['_id']), str(object['ID']), object['item'],
str(object['qty'])
r = ' '.join(read_records)
print(r)
fp.write(r)
fp.close()

我相信这会解决您的问题。

关于python - 如何显示所有数据并将其保存在文本文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52289516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com