Python 迭代打印文件名中的SQL输出
我试图从数据库中提取数据,将每条记录存储在自己的文本文件中。为了正确命名文本文件,我想将文件名作为存储在数据库中的记录的ID写入。我将如何调整以下代码来实现这一点Python 迭代打印文件名中的SQL输出,python,Python,我试图从数据库中提取数据,将每条记录存储在自己的文本文件中。为了正确命名文本文件,我想将文件名作为存储在数据库中的记录的ID写入。我将如何调整以下代码来实现这一点 cur.execute("select postid, flatcontent from openscattachments where hasattachment is not null order by postid;") for i, row in enumerate(cur): with ope
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))
您可以直接解压
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))