Python 写入记录到新的文本文件

Python Write to Record to New Text File

下面的代码将每条记录写入一个文本文件。我想为每条记录创建一个新的文本文件。有没有一种方法可以将唯一字符或数字附加到文件名以强制生成新文件?

import pyodbc
import csv

# Create connection
cnxn = pyodbc.connect(driver="{SQL Server}",server="<server>",database="<database>",uid="<username>",pwd="<password>")
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM <table>")
row = cursor.fetchall()

with open(r"c:/Projects/record.txt", "w") as f:
    csv.writer(f).writerows(row)

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

是的,当然有。只需遍历行并为每次迭代构建不同的文件名。例如,

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()

创建按顺序编号的文件

record1.csv
record2.csv
record3.csv