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

时间:2018-09-12 07:17:21

标签: python mongodb

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()

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

2 个答案:

答案 0 :(得分:0)

您不需要使用with open关闭文件,它会自动处理

尝试使用此功能:

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 my_obj in read:
          read_records = str(my_obj['_id']), str(my_obj['ID']), my_obj['item'], 
          str(my_obj['qty'])
          r = ' '.join(read_records)
          print(r)
          fp.write(r)

答案 1 :(得分:0)

您将重新打开输出文件以在循环的每次迭代中进行写入。每次迭代都会以 write 模式打开一个新文件,覆盖现有的“ 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()

我相信这可以解决您的问题。