[Solved] Python Write to Record to New Text File [closed]


Is there a way that I can append a unique character or number to the file name to coerce a new file?

Yes, of course there is. Just iterate through the rows and build a different file name for each iteration. For example,

import csv
import pyodbc

connStr = (
    r"Driver={SQL Server};"
    r"Server=(local)\SQLEXPRESS;"
    r"Database=myDb;"
    r"Trusted_connection=yes;"
    )
cnxn = pyodbc.connect(connStr)
crsr = cnxn.cursor()

sql = """\
SELECT 101 AS numthing, 'foo' AS txtthing
UNION ALL
SELECT 102 AS numthing, 'bar' AS txtthing
UNION ALL
SELECT 103 AS numthing, 'baz' AS txtthing
"""
crsr.execute(sql)
i = 1
for row in crsr:
    with open('C:/__tmp/Projects/record{0}.csv'.format(i), 'w') as f:
        csv.writer(f).writerow(row)
        i += 1
crsr.close()
cnxn.close()

creates the sequentially-numbered files

record1.csv
record2.csv
record3.csv

solved Python Write to Record to New Text File [closed]