如何在python中为每个sql查询创建单独的csv文件?

时间:2019-03-22 08:10:17

标签: python

我在不同文件中有3个sql查询。我试图一一运行所有sql查询。但每个SQL查询的输出都保存在单个csv文件中。所以我想将每个查询结果保存在单独的csv文件中。

path1 = "D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.txt"
files = glob.glob(path1)
for name in files:
    try:
        with open(name) as f:
            sql_query = f.read()
            cur.execute(sql_query)
            result = cur.fetchall()

            with open("output.csv", 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                a.writerow([i[0] for i in cur.description])
                a.writerows(result)

    except:
        print("error")

2 个答案:

答案 0 :(得分:1)

之所以会这样,是因为您每次都覆盖相同的csv。

path1 = "D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.txt"
files = glob.glob(path1)
i = 1
for name in files:
    try:
        with open(name) as f:
            sql_query = f.read()
            cur.execute(sql_query)
            result = cur.fetchall()

            with open("output_%s.csv" % i, 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                a.writerow([i[0] for i in cur.description])
                a.writerows(result)
            i+=1

    except:
        print("error")

答案 1 :(得分:0)

您继续写入相同的CSV文件。您为什么不尝试这样的事情:


path1 = "D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.txt"
files = glob.glob(path1)
file_list = ["file1.csv", "file2.csv"]

for iterator, name in enumerate(files):
    try:
        with open(name) as f:
            sql_query = f.read()
            cur.execute(sql_query)
            result = cur.fetchall()

            with open(file_list[iterator], 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                a.writerow([i[0] for i in cur.description])
                a.writerows(result)

    except:
        print("error")