David White
David White

Reputation: 113

convert output from sqlite from tuple to list in Python

I am new to programming and am writing a simple python script that will gather some information from a PC for forensic purposes. Some of the information I want is the Chrome history. Basically I need to read the data from the history sqlite database, perform a calculation to convert the time stamp to a human readable format, and then write the data to a CSV file. I have the following code:

connection = sqlite3.connect('c:\history')### need correct path
connection.text_factory = str
cur = connection.cursor()
output_file = open('chrome_history2.csv', 'wb')
csv_writer = csv.writer(output_file,)
headers = ('URL', 'Title', 'Visit Count', 'Last Visit')
csv_writer.writerow(headers)
epoch = datetime(1601, 1, 1)
for row in (cur.execute('select url, title, visit_count, last_visit_time from urls limit 10')): #selects data
        list(row) #convert to list - does not work
        url_time = epoch + timedelta(microseconds=row[3]) #calculates time
        row[3] = url_time #changes value in row to readable time
        csv_writer.writerow(row)
connection.close()

This code returns the error:

TypeError: 'tuple' object does not support item assignment

I understand that I can't manipulate the data in a tuple but I am explicitly converting each row to a list. Can anyone explain a) why list (row) does not work, and b) a better way to do it?

Thanks in advance!

Upvotes: 3

Views: 5018

Answers (2)

ROBOT4321
ROBOT4321

Reputation: 1

Another work around would be like this-->

    conn = sqlite3.connect('library.db')
    conn.row_factory = lambda cursor, row: row[0]
    c = conn.cursor()

    id_sql = 'SELECT emp_id FROM teachtable WHERE teach_name = "%s"' % (name1)
    id_no = c.execute(id_sql).fetchall()
    conn.commit()
    conn.close()
    # This list output can be used to iterate through it in a for loop
    
    # print the first element from the list
    idno = id_no[0]
    print(id_no)

Here's a reference link to understand how "row_factory" object is used to return the query output as a list!

Upvotes: 0

shevron
shevron

Reputation: 3663

I think that:

        list(row) #convert to list - does not work

Should be:

        row = list(row) #convert to list

In addition, you may want to look into using a csv.DictReader object instead of the default reader, as it may be more convenient (and is mutable, unlike the default tuple). See https://docs.python.org/2/library/csv.html#csv.DictReader for detauls.

Upvotes: 2

Related Questions