Skip to content

Instantly share code, notes, and snippets.

@VDK
Created November 5, 2020 07:59
Show Gist options
  • Save VDK/642cd8b6fed423849af2334aff93c36a to your computer and use it in GitHub Desktop.
Save VDK/642cd8b6fed423849af2334aff93c36a to your computer and use it in GitHub Desktop.
importing the txt files from a directory into a mysql database
import os
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="default"
)
mycursor = mydb.cursor()
sql = "INSERT INTO table (page, filename) VALUES (%s, %s )"
directory = r'C:/directory'
for filename in os.listdir(directory):
if filename.endswith(".txt"):
page = open(os.path.join(directory, filename), "r")
val = ( page.read(), filename)
mycursor.execute(sql,val)
mydb.commit()
else:
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment