Python 将列名写入文件
我有一个SQLite DB文件,我正在将DB表中每一列的数据解析为一个.txt文件。目前,它正在将列内容写入文件,但不会提取列名称并写入这些内容。我怎样才能做到这一点,因为我已经尝试使用这个指南,但我似乎无法让它发挥作用。下面是我试图从表中提取列名的代码Python 将列名写入文件,python,python-3.x,sqlite,Python,Python 3.x,Sqlite,我有一个SQLite DB文件,我正在将DB表中每一列的数据解析为一个.txt文件。目前,它正在将列内容写入文件,但不会提取列名称并写入这些内容。我怎样才能做到这一点,因为我已经尝试使用这个指南,但我似乎无法让它发挥作用。下面是我试图从表中提取列名的代码 import sqlite3 from sqlite3 import Error # create a database connection to the SQLite database specified by the db_file
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()
您可以使用
光标。description
保存有关列名的信息:
[……]
cur = cursor.execute('SELECT * FROM test_table LIMIT 100')
col_names = [ name[0] for name in cur.description ]
print (col_names)
[…]光标的输出是什么。您现在得到的描述是什么?根本没有输出,它现在不再写入文件。您没有在任何地方调用
get\u col\u names
,因此您没有输出。您的文件写入代码现在位于get\u col\u names
的return
语句之后,因此它永远不会到达,因此没有文件被写入。它现在正在工作。我设法从DB表中提取每个列名并将其写入文件。然后,我能够提取列数据并在之后将其写入文件。现在开始工作了,谢谢。
cur = cursor.execute('SELECT * FROM test_table LIMIT 100')
col_names = [ name[0] for name in cur.description ]
print (col_names)