簡體   English   中英

Python循環寫入CSV文件

[英]Python Loop writing to CSV files

我正在嘗試為每個查詢輸出生成一個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()

看起來是因為所有SQL數據都被寫入變量“輸出”設置為最后的內容。 因此,變量“輸出”設置為的文件只會被不斷覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM