繁体   English   中英

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

[英]How to create separate csv file for each sql query in 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")

发生这种情况是因为您每次都覆盖相同的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")

您继续写入相同的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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM