Python写入记录到新文本文件

时间:2015-12-10 22:19:37

标签: python pyodbc

以下代码是将每条记录写入单个文本文件。我想为每条记录创建一个新的文本文件。有没有办法可以在文件名中附加一个唯一的字符或数字来强制换新文件?

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)

1 个答案:

答案 0 :(得分:0)

  

有没有办法可以在文件名中附加一个唯一的字符或数字来强制换新文件?

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

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