Mostly Linux & Python syntax notes and hyperlinks.

Friday, January 15, 2010

python: time.strptime() instead of datetime.strptime()

Either one worked correctly from the python prompt, but when I embedded it in another tool,
fdate=time.strptime("SEPTEMBER 19 2010", "%B %d %Y")
worked, and
fdate=datetime.strptime("SEPTEMBER 19 2010", "%B %d %Y")
triggered an exception.

Monday, January 11, 2010

python: import

Here's a good link that explains how to use import.

If I have one file in the directory with only one function that I want to use in another file, I think it's clearer to say this at the top of the other python file:
from my_one_function_file import my_one_function
Then if I stop using that function, I know I can get rid of the import statement. When I look at the import statement, I know exactly why it is there.

The link recommends always using "import", which would mean:
import my_one_function_file
then calling my_one_function via
my_one_function_file.my_one_function()
In general, this recommendation does look like wise practice. It's more object-oriented.

Friday, January 8, 2010

python: mapping one list to another

I have two lists of strings. I want to associate the names of the first list with the values in the second.
Trying to do it with the mapping or dictionary type:
>>> x=['a','b']
>>> x
['a', 'b']
>>> y=['c','d']
>>> z={}
>>> z.fromkeys(x,y)
{'a': ['c', 'd'], 'b': ['c', 'd']}
That's not what I want..  Instead:
>>> d=dict(zip(x,y))
>>> d
{'a': 'c', 'b': 'd'}
>>>
That's as close as I can get it.
>>> d['a']
'c'
>>> d['b']
'd'
It seems awkward, but if you put it in a loop, it looks fine:
 >>> x=['a','b','c','d','e']
>>> y=['q','r','s','t','u']
>>> z=zip(x,y)
>>> z
[('a', 'q'), ('b', 'r'), ('c', 's'), ('d', 't'), ('e', 'u')]
>>> d=dict(z)
>>> d
{'a': 'q', 'c': 's', 'b': 'r', 'e': 'u', 'd': 't'}
>>> for key in x:
...   print key, "=", d[key]
...
a = q
b = r
c = s
d = t
e = u
>>>

python: looping through filenames in a directory

import os
...
dirname=os.getcwd()
ext_name=".txt"
...
try:
        for file in os.listdir(dirname):
            if file.endswith(ext_name):
                #do whatever
except:

Thursday, January 7, 2010

python: setting two things at once, links for getopt, csv.reader,

The code I need to modify uses csv.reader and getopt

and it can set two values at once!
 >>> a,b="c","d"
>>> a
'c'
>>> b
'd'
>>> a,b='f g'.split()
>>> a
'f'
>>> b
'g'