students = conn.execute(select([Students])).fetchall() results = conn.execute( select( [ Results.c.student_id, Results.c.answer, Results.c.graph_id, Answers.c.answer, Questions.c.question, StudentsTest.c.dataset, ] ) .select_from( Results.join(Students, Students.c.student_id == Results.c.student_id) .join(StudentsTest, StudentsTest.c.student_test_id == Results.c.student_test_id) .outerjoin(Questions, Questions.c.question_id == StudentsTest.c.question_id) .outerjoin(Answers, Answers.c.answer_id == Results.c.answer) ) .where(Students.c.opt_in == "na") ).fetchall() results = [[x.replace(",", "") if type(x) == type("s") else x for x in t] for t in results] results = [["Student_id", "answer", "graph_id", "answer_text", "question", "dataset"]] + results with open("student_table_list.csv", "w", newline="") as csvfile: spamwriter = csv.writer(csvfile, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL) [spamwriter.writerow(s) for s in students] with open("results_table_list.csv", "w", newline="") as csvfile: spamwriter = csv.writer(csvfile, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL) [spamwriter.writerow(r) for r in results]