Breaking the barrier of a broken paradigm... part 1

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Mar 25 12:40:40 EDT 2008


john s. a écrit :
> On Mar 24, 9:39 pm, "Ryan Ginstrom" <softw... at ginstrom.com> wrote:
>>> On Behalf Of john s.
>>> import os, sys, string, copy, getopt, linecache
>>> from traceback import format_exception
>>> #The file we read in...
>>> fileHandle = "/etc/passwd"
>>> srcFile = open(fileHandle,'r')
>>> srcList = srcFile.readlines()
>>> #yah, a for loop that "iterates" through the file of "lines"
>>> for i in srcList:
>>>     strUsr = string.split(i,":")

Erroneous hungarian notation is Bad(tm). And FWIW, the convention is to 
use all_lower for variable names.

(snip consideration about using str.methods instead of string functions 
etc...)

>> How about for starters:
>>
>> import os
>>
>> for line in open("/etc/passwd"):

NB : this idiom relies on the VM automatically closing files, which is 
not garanteed on each and every implementation (IIRC, jython won't do 
it). This is ok for Q&D throwaway scripts targeting CPython, but should 
not go into production code.

>>     user, _pwd = line.split(":")
>            ^----- Ok this one here we are taking a string spliting it
> into to variables...
>            user gets one (the first) and _pwd gets to hold the
> "leftovers"?

Quite. user gets the first, _pwd gets the second. If you have more than 
2 fields (IOW : more than one ':') in the line, it will raise.

If you want to make sure this will still work with more than 2 fields, 
you can use the optional max_split arg:

   user, rest = line.split(':', 1)

>>     user_home = os.path.join("/expirt/home", user)
>>
>>>         try:
>>>             os.makedirs('usrHome' )
>>>         except Exception, e:

Better to be as specific as possible wrt/ exceptions you want to handle. 
Remember that some exceptions are better left alone (hint: sys.exit 
works by raising an exception...)

>>>             print e
>>     if os.path.exists(user_home):
>                     ^----- are(n't) exists and os.path.isadir
> interchangable?

They're not. If you want to be bulletproof, you'll have to use 
os.path.isdir *and* handle the case where user_home exists and is not a 
directory.


HTH



More information about the Python-list mailing list