我试图从数据库中提取数据存储每个记录在自己的文本文件中。为了正确命名文本文件,我想将文件名写为存储在数据库中的记录的ID。我如何调整以下代码来做到这一点?
cur.execute("select postid, flatcontent from openscattachments where hasattachment is not null order by postid;")
for i, row in enumerate(cur):
with open('{}.txt'.format(i), 'w') as f:
f.write('{}'.format(row))
答案 0 :(得分:1)
您可以直接解压由cur
返回的元组,而不是使用enumerate
。
sql = "select postid, flatcontent from openscattachments where hasattachment is not null order by postid;"
cur.execute(sql)
for (postid, flatcontent) in cur:
with open('{}.txt'.format(postid), 'w') as f:
f.write('{}'.format(row))