4 Replies - 791 Views - Last Post: 19 May 2011 - 11:26 AM Rate Topic: -----

#1 brennydoogles  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 59
  • Joined: 23-June 09

Having an issue comparing file names

Posted 18 May 2011 - 08:14 PM

Hey all, I am having an issue comparing strings in a program I'm writing. Basically, I'm looping through the files in a folder which is set up as follows:
Each folder contains a photo album. The name of the folder is the album name.
Each folder contains a file called cover.txt, which holds the filename of the cover image.
Each folder also contains a file called description.txt, which holds the album description.

The goal of my program is to loop through each directory and insert data about the albums into a database, where they will populate the album section of a website. Here is my code (with DB info removed):
import os
import string
import MySQLdb
import re

def escape(input):
    return input.replace('\'', '\\\'')

def executeQuery(query):
    conn = MySQLdb.connect (host = "localhost", user = "root" , passwd = "****" , db = "****")
    cursor = conn.cursor()
    cursor.execute(query);
    results = cursor.fetchone()
    while results != None:
        yield results
        results = cursor.fetchone()
    cursor.close()

def readFileAsString(fileName):
    try:
        f = open(fileName, 'r')
        output = f.read()
        print output
        return output
    except:
        return "Error"

def checkIfAlbumExists(albumName):
    exists = False
    for i in executeQuery("select ID from ALBUM where ALBUM.TITLE = '%s'" % (escape(albumName))):
        exists = True
    return exists

def checkIfPhotoExists(fileName, albumName):
    exists = False
    for i in executeQuery("select ID from PHOTO where PHOTO.FILE_NAME = '%s' and PHOTO.IMAGE_SUBPATH = '%s'" % (escape(fileName), escape(albumName))):
        exists = True
    return exists

def insertAlbum(albumName, description):
    query = "insert into ALBUM(TITLE, DESCRIPTION) values('%s', '%s')" % (escape(albumName), escape(description))
    conn = MySQLdb.connect (host = "localhost", user = "root" , passwd = "****" , db = "****")
    cursor = conn.cursor()
    cursor.execute(query)
    query = "select * from ALBUM where ALBUM.TITLE = '%s'" % (escape(albumName))
    cursor.execute(query)
    results = cursor.fetchone()
    id = results[0]
    cursor.execute("commit")
    cursor.close()
    return id

def insertPhoto(fileName, albumName):
    query = "insert into PHOTO(FILE_NAME, FILE_EXTENSION, IMAGE_SUBPATH) values('%s', '%s', '%s')" % (escape(fileName.split('.')[0]), escape(fileName.split('.')[1]), escape(albumName))
    conn = MySQLdb.connect (host = "localhost", user = "root" , passwd = "****" , db = "****")
    cursor = conn.cursor()
    cursor.execute(query)
    query = "select ID from PHOTO where PHOTO.FILE_NAME = '%s'" % (escape(fileName.split('.')[0]))
    cursor.execute(query)
    results = cursor.fetchone()
    id = results[0]
    cursor.execute("commit")
    cursor.close()
    return id

def insertAlbumRelation(photoId, albumId, isCover):
    conn = MySQLdb.connect (host = "localhost", user = "root" , passwd = "****" , db = "****")
    cursor = conn.cursor()
    query = "select * from IN_ALBUM where IN_ALBUM.PHOTO_ID = '%s' and IN_ALBUM.ALBUM_ID = '%s'" % (photoId, albumId)
    cursor.execute(query)
    results = cursor.fetchone()
    if(results == None):
        query = "insert into IN_ALBUM(PHOTO_ID, ALBUM_ID, IS_COVER) values('%s', '%s', '%s')" % (photoId, albumId, isCover)
        cursor.execute(query)
        cursor.execute("commit")
    cursor.close()

if __name__ == "__main__":
    imageRoot = "/home/brendon/Web/images"
    for dir in os.walk(imageRoot):
        currentDir = dir[0]
        files = dir[2]
        if currentDir != imageRoot:
            isText = False
            albumName = os.path.split(currentDir)[1]
            if(os.path.exists(os.path.join(currentDir, "description.txt"))):
                description = readFileAsString(os.path.join(currentDir, "description.txt"))
            if(os.path.exists(os.path.join(currentDir, "cover.txt"))):
                cover = readFileAsString(os.path.join(currentDir, "cover.txt"))
            if(checkIfAlbumExists(albumName)):
                for i in executeQuery("select * from ALBUM where ALBUM.TITLE = '%s'" % (escape(albumName))):
                    albumId = i[0]
                    break
##                print "Album Exists with ID of %s" % (albumId)
            else:
                albumId = insertAlbum(albumName, description)
            for file in files:
                isCover = 0
                print "file = %s, cover = %s, isCover = %d" % (file, cover, isCover)
                if file == cover:
                    isCover = 1
                    print "file = %s, cover = %s, isCover = %d" % (file, cover, isCover)
                if(checkIfPhotoExists(file, albumName)):
                    if(file.split('.')[1] != "txt"):
                        for i in executeQuery("select * from PHOTO where PHOTO.FILE_NAME = '%s'" % (escape(file))):
                            photoId = i[0]
                            break
                    else:
                        photoId = "empty"
                else:
                    photoId = insertPhoto(file, albumName)
##                print "Album ID = %s, Photo ID = %s" % (albumId, photoId)
                if(photoId != "empty"):
                    insertAlbumRelation(photoId, albumId, isCover)
                



Any thoughts?

Is This A Good Question/Topic? 0
  • +

Replies To: Having an issue comparing file names

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6037
  • View blog
  • Posts: 23,432
  • Joined: 23-August 08

Re: Having an issue comparing file names

Posted 19 May 2011 - 03:36 AM

Narrow down your problem and provide more details as to where in your code things aren't working as you expect. You may need to trim a trailing newline off of the data you've read from the file.
Was This Post Helpful? 1
  • +
  • -

#3 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Having an issue comparing file names

Posted 19 May 2011 - 05:41 AM

And your problem is....?
Was This Post Helpful? 0
  • +
  • -

#4 brennydoogles  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 59
  • Joined: 23-June 09

Re: Having an issue comparing file names

Posted 19 May 2011 - 06:13 AM

View PostJackOfAllTrades, on 19 May 2011 - 04:36 AM, said:

You may need to trim a trailing newline off of the data you've read from the file.


I feel stupid. I had been doing that in __main__ at one point, but decided to move it up to the read() function. Apparently I deleted it from __main__ and forgot to add it into read(). I guess that's what happens when you have a newborn scrambling your brain! Thanks!
Was This Post Helpful? 0
  • +
  • -

#5 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: Having an issue comparing file names

Posted 19 May 2011 - 11:26 AM

Another point about your code: In a lot of functions you open a connection to the database, but you don't close it at the end of the function. This means you have open connection object lying around in memory until the garbage collector decides to delete them.

Maybe you should explicitly close them as you did with the cursor objects
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1