This is a basic example in python made from documentation!
Please note that no try catch
blocks are used (which is bad), but it should work. You could end up with UTF-8 errors, IO errors or stuff I didn't bother about (I will revise the code if necessary) ... Anyway, save the code below into a file (let's say "myfile.py"), put the correct information in order to connect to your database, replace "/path/to/files/" with a real path and finally run "python myfile.py" in your console.
If you have lots of files this could take a bit, and mind your system's memory status. Each file will be read and put into the system's memory. If the file size exceeds the memory limits, the script will probably crash. If the files are small you are fine.
Test it first!
Requirements: python with psycopg2 installed
import os
import psycopg2
connection = psycopg2.connect(database='my_db', user='my_postgres_user', password='my_postgres_pass')
cursor = connection.cursor()
cursor.execute('DROP TABLE IF EXISTS text_files;CREATE TABLE text_files (id SERIAL UNIQUE PRIMARY KEY, file_name TEXT, file_content TEXT);')
directory = os.path.normpath('/path/to/files/')
for root, dirs, files in os.walk(directory):
for filename in files:
print filename
with open(os.path.join(root, filename), 'rb+') as f:
cursor.execute('INSERT INTO text_files (file_name, file_content) VALUES (%s, %s);', (filename, f.read()))
f.closed
connection.commit()
cursor.close()
connection.close()