0

I have 3 sql queries in different files. I tried to run all sql queries one by one. but output of every sql query is saving in single csv file. so i want to save each query result in separate csv file.

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")
1
  • CSV's are written to the same file because you open them with the same open("output.csv", 'w') statement. Commented Mar 22, 2019 at 8:16

2 Answers 2

1

That is happening because you overwrite the same csv every time.

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")
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the help. i need one more requirement. If i want to to generate csv file like query name e.g. - if "survey_cust.txt" query runs then csv file will be generate the name like "survey_cust.csv". how to do this, can you please help me to implement this logic?
@amisha csv_name = name.split('/')[-1].split('.')[0] with open("output_%s.csv" % csv_name, 'w') as fp:
0

You keep writing to the same CSV file. Why don't you try something like this:


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.