Python循环写入CSV文件

时间:2019-06-27 22:59:18

标签: python

我正在尝试为每个查询输出生成一个csv文件。我在单个SQL文件中有多个选择查询(queries.sql),并且正在遍历它以在数据库中执行并将每个查询输出写入其自己的csv文件。当我执行代码时,所有查询都在数据库中执行,但是只有最后一个查询结果集正在写入csv文件,其余所有csv文件都没有记录。任何帮助表示赞赏。

  col_pattern = "(^|[_-])SSN#?($|[_-])|^SS#?$|(^|[_-])(SSN|SOC.*SEC.*).?(ID|NO|NUMBERS?|NUM|NBR|#)($|[_-])|^SOCIAL.?SEC(URITY)?#?$"
SQL = "select OWNER||'_'||TABLE_NAME||'_'||column_name from ALL_TAB_COLS where REGEXP_LIKE (column_name, :1) and owner NOT IN ('SYS','SYSMAN') order by table_name,column_name"
cursor.execute(SQL,(col_pattern,))
for row_data in cursor:
    if not row_data[0].startswith('BIN$'):
        fileName = row_data[0]
        csv_file_dest = "/u01/exp/test/identity/csvdata/"+ fileName + ".csv"
        outputFile = open(csv_file_dest,'w') # 'wb'
        output = csv.writer(outputFile, dialect='excel')

f = open('/u01/exp/test/identity/queries.sql')
full_sql = f.read()
sql_commands = full_sql.replace('\n', "").split(';')[:-1]
#print(sql_commands)
for sql_command in sql_commands:
    curs2 = cursor.execute(sql_command)
    if printHeader: # add column headers if requested
        cols = []
        for col in curs2.description:
            cols.append(col[0])
        output.writerow(cols)
    for row_data in curs2: # add table rows
        output.writerow(row_data)
    outputFile.close()

1 个答案:

答案 0 :(得分:0)

这看起来像是因为所有SQL数据都被写入变量“输出”设置为最后的内容。因此,变量“输出”设置为的文件只会被不断覆盖。

相关问题