[Tutor] Code critique and unicode questions

Ole Jensen learning.python at dbmail.dk
Tue Aug 24 14:02:33 CEST 2004


Hello list

I was hoping you could take a look at the attached Python program. It is
actually the first purposeful prorgram I have made :) and as I intend to
get my grandmother (who knows nothing about computers) to use it I would
prefer that nothing unexpected happens... So if there is some part of
the program that is likely to do anything... well, funny! Please let me
know.
The printouts are in Danish, although I have not translated them I have
written quotes that explains the printouts in a more concise manner, so
it should be understandable.

I would also very much like to know if there are some elements of my
coding that is either good or bad, e.g. in the function SpcfName I have
two triple quoted printouts that is not indented correctly, in order to
align it properbly in the program output. Is this something I should NOT
do?
Are there anything else?

Also I have two questions concerning Unicode.
1) Is there some encoding scheme (e.g. # -*- coding: Latin-1 -*-) that
would make the u"strings" unnecessary? If I remove the Unicode prefix
the special characters (æ, ø, å, etc) get messed up.
2) If the user enters a special character (like above), the chacteres in
the outputted filename gets even more messed up (it looks like something
from the greek alphabet!).
I do not know if there are any limitations to the os.rename() function
concerning special characters, but if it is possible to create
filenames/folders with special characters how do I do that?
I guess that the flaw could also be from raw_input () as I do not prefix
that with the Unicode escape character (i.e. u"string").
Any help with this wil be greatly appreciated.

I just thought of another question! The camera is often unplugged from
the PC, because of this I presume its drive letter can change, if for
example a USB memory stick can 'take' the drive letter that the camera
usually have! Is there any way find out what drive letter the camera is
assigned to instead of just geussing it to be G:? Maybe from the drive
label?

TIA
Ole Jensen
-------------- next part --------------
# -*- coding: Latin-1 -*-

####################################################
#           Program made by Ole Jensen             #
#Contact                                           #
#Email: learning.python at dbmail.dk                  #
#Web: http://dbhome.dk/learningtoprogram/intro.html#
#==================================================#
#             Completed 24. Aug 2004               #
#==================================================#
# Filename:                                        #
#        fetch pictures from digital camera.py     #
#                                                  #
# Description:                                     #
# This program lets you fetch the pictures from    #
# your digital camera, and names the pictures      #
# to what the user inputs.                         #
# It is not limited to do only this, as the        #
# file extension will be kept, this program        #
# kan move all files from a Source Folder          #
# to a Destiantion Folder.                         #
#==================================================#
#         Made and testet in Python 2.3.4          # 
####################################################


from os import rename, listdir, mkdir
from os.path import exists
from time import sleep

# for testing: "C:/Documents and Settings/Ole/Desktop/pic test/" 
SRC_FOLDER = "G:/CAMERA"    # Because camera is hotswitchable
                            # its drive letter may change
DEST_FOLDER = "C:/Documents and Settings/Ole/Desktop/Pictures/"


def SpcfName():
    """This function prompts the user to input a valid name
    i.e. a foldername that is not in use, and if the name
    contains any invalid tokens"""

    print u"""
Du skal starte med at skrive hvad billederne skal
kaldes. Prøv at give dem navn efter anledningen eller
hvor billerne er taget og hvornår m.m."""
    print 2* "\n"
    # User inputs what the pictures are to be called
    name = raw_input("Hvad skal billederne kaldes?\n>>>")
    # If the name is already a folder
    # make sure not to delete it!
    if exists(DEST_FOLDER+name):
        # Error message, and try again
        print u"""
Dette navn '%s' er allerede brugt. Tilføj evt. datoen
fra billederne blev taget for at give et andet navn

    Vent lidt!""" % name
        # Delay next prompt til the user has read the error message
        sleep(10)
        # Make the function recursive until a valid name has been given
        name = SpcfName()
        
    elif not ValidToken(name):
        # If name contains invalid filename tokens
        # show this error message:
        print u"Du må desværre ikke bruge nogen af disse tegn:"
        print u"\\ - bagvendt skråstreg."
        print u"/ - alm. skråstreg."
        print ": - colon."
        print "* - stjerne."
        print u'" - gåseøjne/dobbelt citeringstegn.'
        print u"? - spørgsmålstegn"
        print "< - mindre end"
        print u"> - større end"
        # Recursive until the name is valid
        name = SpcfName()
    else:
        # run the function that actually moves the pictures
        Move(name)

def ValidToken(str):
    """Returns True if the string contains only valid (win32)
    letters and tokens"""

    # according to winXP Home these are invalid tokens:
    invalid = ("\\", "/", ":", "*", "?", '"', "<", ">")
    # Set flag. Presumed to be valid until proven otherwise
    valid = True
    # Tests if there is at least 1 invalid character
    for item in invalid:
        if item in str:
            # The string contains an invalid token
            valid = False
            # No reason to continue the loop.
            break
    return valid

def FileExt(file):
    """The file must be given as a string.
    Small function that return the file extension. 
    Presumes the file extension to be all characters after
    the last dot [.]"""
    return file.split(".")[-1]

def CreateFilename(name, number, file):
    """Returns a string holds that the first 10 characters from 'name',
    adds a 'number' padded with zero's and keeps the original file
    extension from 'file'"""
    filename = name[:10] + "%04d" % number + "." + FileExt(file)
    return filename

def Move(name):
    """Creates a new folder in DEST_FOLDER called 'name'.
    And moves all files from SRC_FOLDER into this one."""

    # Import filenames into a list
    lstFolder = listdir(SRC_FOLDER)
    # create the folder where to save the pictures
    endFolder = DEST_FOLDER+name+"/"
    mkdir(endFolder)
    i = 1
    for file in lstFolder:
        if file == "Thumbs.db":
            pass
        else:
            rename(SRC_FOLDER+file, endFolder + CreateFilename(name, i, file))
            i += 1


if __name__ == "__main__":
    print 5 * "\n"
    SpcfName()


More information about the Tutor mailing list