[Tutor] How to... (a) write to files, (b) use try/except

Kent Johnson kent37 at tds.net
Sun Feb 10 02:33:21 CET 2008


Rob Stevenson wrote:

>             Title = book.ProductName
>             printstring = isbn + "\t" + book.ProductName + "\t" + 
> book.Authors.Author + "\tUsed from...\t" + book.UsedPrice +  "\tNew 
> price\t" + book.OurPrice
>             print printstring
>             print printstring >> fle
>         except:
>            ignorance='notBliss'
> fle.close

Should be fle.close(), you need the parentheses to make a function call.

> Now I have two problems
> 
> 1) the file c:\321.txt (which does exist) never gets written to.  I also 
> tried using
> 
> fle.write(printstring)
> 
> and fle.writeline(printstring) but they didn't do anything either.

Assuming that there are some results, it is probably the lack of a 
proper close that is the problem.
> 
> 2)  if any of the function calls from amazon.py, such as book.UsedPrice 
> fails then the rest of the details that may well have been retreived for 
> that get lost in the jump to the except block.  I'd really like to get 
> whatever info I can on the printstring assignment line and ignore any 
> errors, perhaps substituting 'none' instead of a retrieved value.

Instead of book.UsedPrice you can say getattr(book, 'UsedPrice', 'none') 
which will return the string 'none' if the attribute is not available.

> Also, a point of nettiquette for this list - how do I say thanks to 
> people - not to the list, but in direct emails?

I think either way is fine.

Kent


More information about the Tutor mailing list