[Tutor] Doubts galore.

Steve Willoughby steve at alchemy.com
Thu Jun 10 17:26:28 CEST 2010


On Thu, Jun 10, 2010 at 08:44:56PM +0530, prasad rao wrote:
> Hi
> 
> def cript(doc=None,data =None):
>    if  doc==None and data==None:doc=sys.agv1

Never NEVER compare for equality with None.

What you want is:
     if doc is None and data is None:

Also, what is "sys.agv1"?  Did you mean sys.argv[1]?

>    elif doc:
>         data=open(doc,'r').read()
>         data_c= binascii.hexlify(data)
>    else:data_c= binascii.hexlify(data)
>    if doc:
>         q=tempfile.TemporaryFile()
>         q.write(data_c)
>         os.rename(q,doc)
>         return
>    return data_c

It would probably be cleaner to use one-line 
conditional statements (sparingly) where they make
sense on their own, but not to mix multi-line and
single line styles in the same if-else structure.

I'm not sure the logical flow through there
does what you think it does, though.

> cript(doc='./language.txt')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 10, in cript
> TypeError: coercing to Unicode: need string or buffer, file found
> 

Is this the actual code or did you retype it?
It has some typos which makes me wonder.  If you copy/paste
the actual code that can remove any confusion introduced
by simple typing mistakes, so we are sure we're all looking
at the same thing here.

> 1)Why I got the above error message with  the above function?How to correct it?

The binascii.hexlify() function converts a binary data string into
hexadecimal digits.  You didn't give it a data string to work from,
you gave it an open file object.  You'll need to actually read the
data from the file and give that to the function.

> 2)Is it reasonable to have 2 if blocks in a function as above?

Sure

> 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my
>   file as I expect it to do)

It creates a TEMPORARY file.  That means you can expect it to
exist on disk until you close it, and then if at all possible,
it will automatically be destroyed for you.  Hence "temporary".
Depending on your platform, while there will be a physical disk
file, it might not even show up in a directory or be openable by
other applications.

If you want a file to not be temporary, use open() to create it.
> 
> Please someone enlighten me.
> 
> Prasad
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list