PYTHON: Trying to get every .sql file in a directory as an input. So I can open() then read() each one

3069 views python
-3

import os

from os import walk

import psycopg2

take = []

for root,dirs,files in walk('C:\\Users\\sebastian\\Documents\\Code\\sql_tests'):

    for file in files:
        if file.endswith('.sql'):
            take = os.path.join(root,file)
            print(take)

f = open(takes)

print(f)

full_sql = f.read()

print (full_sql)

print take:

C:\Users\sebastian\Documents\Code\sql_tests\sql_test.sql

C:\Users\sebastian\Documents\Code\sql_tests\sql_test2.sql

print take[0]

C

Problem is that it thinks each character in the directory is an element of the list. Can I create a new list from that one separated by the new line between them?

answered question

do you want a list like [file1.sql ,file2.sql ,file3.sql....] ?

@GiovaniSalazar yes. because then I could use a for loop to go through each directory... im thinking something like this: for script in file_list: with open(script, 'r') as f: sql_to_do = f.read() print(sql_to_do)

1 Answer

10

Here an example , I made changes when the way you build the list

import os
from os import walk
import psycopg2

take = []
for root,dirs,files in walk('D:\\MY\\PAHT\\ALLSQLFILES\\'):
    for file in files:
        if file.endswith('.sql'):
            #take = os.path.join(root,file)
            take.append(os.path.join(root,file))
print(take)

posted this

Have an answer?

JD

Please login first before posting an answer.