gpt4 book ai didi

python - 将列名写入文件

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

我有一个 SQLite 数据库文件,我正在将数据库表中每一列的数据解析为 .txt 文件。目前,它正在将列内容写入文件,但不会提取列名称并写入这些名称。当我尝试使用本指南 Is there a way to get a list of column names in sqlite? 时,我该怎么做?但我似乎无法让它发挥作用。这是我的代码,尝试从表中提取列名。

import sqlite3
from sqlite3 import Error


# create a database connection to the SQLite database specified by the db_file
def create_connection(db_file,detect_types=sqlite3.PARSE_DECLTYPES):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)

return None

# Query specific rows in the sms table
def select_data(conn):
cur = conn.cursor()

cur.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms")
print("Writing the contents of the sms table to an evidence file")
print("\t")

# Trying to pull out column names from db table
def get_col_names():
conn = sqlite3.connect("mmssms.db")
c = conn.cursor()
c.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms")
return [member[0] for member in c.description]



# Write the data to a smsEvidence.txt file
with open('EvidenceExtractionFiles/smsInfo.txt', 'a+') as f:
rows = cur.fetchall()
for row in rows:
#print(row)

f.write("%s\n" % str(row))
print("SMS Data is written to the evidence File")



# path to where the db files are stored
def main():
database = "H:\College Fourth Year\Development Project\Final Year Project 2018\mmssms.db"

# create a database connection
conn = create_connection(database)
with conn:

# print("Query specific columns")
select_data(conn)
# close db connection
if(conn):
conn.close()
print("Database closed")


if __name__ == '__main__':
main()

最佳答案

您可以使用 cursor.description 来保存有关列名称的信息:

[...]

cur = cursor.execute('SELECT * FROM test_table LIMIT 100')
col_names = [ name[0] for name in cur.description ]
print (col_names)

[...]

关于python - 将列名写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48620255/

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