将完整数据写入文件

时间:2018-02-03 13:59:23

标签: python sqlite

我有一个python脚本,它解析SQLite数据库表中的数据并将其写入文本文件。

它正在发挥作用,但它一遍又一遍地写下最后一行。我试过使用" a +"要附加到文件上的参数但它似乎在此之前错过了所有内容并且只写了最后一行。是否有理由不将控制台中的所有已解析数据保存到文件中。

# Script that parses data from the sms table contained in the mmssms database (text message database)

# import statements
import sqlite3, datetime
from sqlite3 import Error
import csv


# create a database connection to the SQLite database specified by the db_file
def create_connection(db_file):
    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, date, date_sent, read, type, body, seen FROM sms")
    print("Outputting the contents of the sms table within the mmssms.db database file")
    print("\t")

    # Write the data to a txt file
    with open('smsEvidence.txt', 'a+') as f:
        rows = cur.fetchall()
        for row in rows:
            print(row)
        f.write("%s\n" % str(row))
        print("Data is Written To txt 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()

0 个答案:

没有答案