0

I am using pyhton 2.7 to compare datasets. I call a select statement to pull from the two tables. str(row[4]) is always blank. I need to always write a "T" into that column.

Is there a way to write into str(row[4]) during the g.write statement I use in the below code?

This is part of my code:

## This is used to connect to our database and run the sql statement.
def RunSQLStatement(sql):
    conn = psycopg2.connect(Connect2DB())
    cursor = conn.cursor()
    cursor.execute(sql)
    alias_data = cursor.fetchall()
    cursor.close()
    conn.close()
    return alias_data

def selectFoisp():
    with open(outTemp_file, 'w') as g:
        strGetDiffer = """SELECT c.foi_id, c.title, c.feat_type, c.feat_subtype, c.upd_type, p.foi_id, p.title
    FROM foisp c, foisp_prior p
    WHERE (c.foi_id = p.foi_id)
    AND (c.title <> p.title)"""

    extract_rows = RunSQLStatement(strGetDiffer)

    for row in extract_rows:
        g.write(str(row[0]) + ',' + str(row[1]) + ',' + str(row[2])  + ',' + str(row[3]) + ',' + str(row[4]) + ',' +  str(row[5]) + ',' + str(row[6]) + '\n')
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25
Mike Hirschmann
  • 139
  • 1
  • 1
  • 7

2 Answers2

2
g.write(str(row[0]) + ',' + str(row[1]) + ',' + str(row[2])  + ',' + str(row[3]) + ', T,' +  str(row[5]) + ',' + str(row[6]) + '\n')

or with format method:

g.write("{0}, {1}, {2}, {3}, {4}, {5}, {6}\n".format(row[0], row[1], row[2], row[3], "T", row[5], row[6])
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25
1

If it is always blank, why don't you just replace str(row[4]) with 'T'? (as Michael has done)

That said you should be able to directly manipulate row[4] in your loop:

for row in extract_rows:
    row[4] = 'T'
    g.write(str(row[0]) + ',' + str(row[1]) + ',' + str(row[2])  + ',' + str(row[3]) + ',' + str(row[4]) + ',' +  str(row[5]) + ',' + str(row[6]) + '\n')

Furthermore you should look into using the CSV module:

import csv
writer = csv.writer(g)
for row in extract_rows:
    row[4] = 'T'
    writer.writerow(row)

This will automatically sort out an iterable into the format you have specified (comma separated, although you can change some parameters if you want it to be separated with something else.) so you don't have to do lengthy string concatenations. It looks much cleaner that way as well.

NDevox
  • 4,056
  • 4
  • 21
  • 36