Names to MySQL db – Python

I have a very long list of files that are named like this….


So this small script will take the names and put them on a database.

# sends all the information to the db. For not, just look at the names and then
# add the names and the manufacturers.

from MySQLdb import connect
from os import listdir
from re import sub

# location of files
str_file_dir = 'withCarriers/'

# connect to db
db_con = connect(host='myHost',

# Get cursor to then write commands
db_cur = db_con.cursor()

# create a table
    db_cur.execute('''CREATE TABLE t_man_dev(manuf VARCHAR(50),
                                             dev VARCHAR(50))
                                             CHARACTER SET=utf8''')
    print 'Done Goofed, it already exists'

# now go through the directory and get all the names of the manufacturers and
# the devices.

for str_each_file in listdir(str_file_dir):
    if str_each_file.endswith('.txt'):
        list_name_comps = str_each_file.split('_',1)

        str_the_manu = list_name_comps[0]
        str_the_dev = sub('\.txt','',list_name_comps[1])
        db_cur.execute('''INSERT INTO t_man_dev VALUES("%s","%s")''' %
        print str_the_manu

# making sure it all get commited.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s