mysql - Running a Python Script to read info. from a new .txt file being generated at a known location every 1 sec -
my scenario: have known location(directory/path) .txt file going generated every 1 sec, need copy content (contents in format can used directly put in mysql query) , put in mysql query in python script. need keep doing continuously, i.e.,non-stop & always.
the script like:
import mysqldb mydb = mysqldb.connect(host="ip_add", user="uname", passwd="pass", db="db_name") cursor = mydb.cursor() #need add things below- sql = """insert table_name values('%d', 'dummy%d')""" % (i, i) //add here ? cursor.execute(sql) mydb.commit() mydb.close()
problem: don't know how go making such script running always, , have mysql connection open once, while there goes on constant scan of known folder/directory/path new text file , keep reading info. contains , put mysql insert query. [a thing don't need format text file's contents, need read whatever contains.]
please !
regards, chirayu
import mysqldb import os import time stat import st_mtime time_to_sleep = 1 # avoid cpu burning mydb = mysqldb.connect(host="ip_add", user="uname", passwd="pass", db="db_name") cursor = mydb.cursor() last_date = 0 while true: # or want stop condition time.sleep(time_to_sleep) stat = os.stat(filename) if stat[st_mtime] > last_date: # check last modification date last_date = stat[st_mtime] # if more recent, store last date open(filename) f: # open file sql = f.read() # put content in sql data base if sql: cursor.execute(sql) mydb.commit() mydb.close()
Comments
Post a Comment