Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old February 19th, 2013, 02:32 PM
dkoleary dkoleary is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2013
Posts: 11 dkoleary User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 h 45 m 47 sec
Reputation Power: 0
File manipulation (try: except: finally:)

Hi;

Still trying to learn python. I'm playing around with files now. The books/tutorials that I've been reading suggest having a 'finally:' clause to the try/except to close the file. What I'm trying, though, doesn't seem clean to me:

Code:
#### imports:
import sys

file = '/etc/servces'
try:
   fo = open(file)
except:
   print 'no such file'
   sys.exit(1)
finally:
   fo.close()

print 'you made it this far!'


The 'file' parameter is intentionally incorrect. At this particular juncture, I'd like to just print 'no such file' and exit. Yet, as the docs suggest, the finally: clause gets executed even with the sys.exit.

Code:
$ ./tn.py
$ ./tn.py
no such file
Traceback (most recent call last):
  File "./tn.py", line 22, in <module>
    fo.close()
NameError: name 'fo' is not defined


Is there a right way to do this? Basically, I'm looking for something akin to the perl

Code:
finally:
   fo.close() if (defined(fo))  # to steal some code from perl


I'd like to learn the right way to do this from the start instead of having to unlearn things later.. been down that road a wee bit too many times

Thanks for any hints/tips/suggestion.

// a few minutes later:

Just read in the python cookbook that the open shouldn't be in the try statement.. so, the test of the open would be the attempt to read the file, then? Does that catch all errors (permission problems, file not there, etc?) The code in the cookbook says:

Code:
fo = open(file)
try:
   for line in fo:  # chto-nibud' slyuchaets'ya zdes'
finally:
   fo.close()


// and yet a few minutes more:

I found something that works; but it seems kind of kludgey ( I refer the reader to my earlier statement about learning the right way...)

Code:
#### imports:
import sys

file = '/etc/servces'
try:
   fo = open(file)
except IOError:
   print 'no such file'
   sys.exit(1)
   
try:
   lines = fo.readlines()
finally:
   fo.close()

print 'you made it this far!'


So, there're two try stanzas: one to check for errors on the file and the other to check on errors for reading the file. It seems like there should be a cleaner way of doing that.

Once again, thanks for any hints/tips/suggestions.

// and yet later still (last time, I promise)

I think I came up with *a* right answer. Not sure if it's *the* right answer:

Code:
#### imports:
import sys

file = sys.argv[1]
try:
   fo = open(file)
   try:
      lines = fo.readlines()
   except:
      print "Can't read file:", file
   finally:
      fo.close()
except:
   print "Can't open file:", file
   sys.exit(1)
   
print 'you made it this far!'


execution:

Code:
$ ./tn.py /etc/services
you made it this far!
$ ./tn.py /etc/servces 
Can't open file: /etc/servces


That seems to satisfy the desire. Is that the accepted way to go about error checking file manipulation?

Thanks again.

Doug O'Leary

Reply With Quote
  #2  
Old February 19th, 2013, 03:16 PM
Scorpions4ever's Avatar
Scorpions4ever Scorpions4ever is offline
Banned ;)
Dev Shed God 9th Plane (9000 - 9499 posts)
 
Join Date: Nov 2001
Location: Woodland Hills, Los Angeles County, California, USA
Posts: 9,406 Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level)Scorpions4ever User rank is General 46th Grade (Above 100000 Reputation Level) 
Time spent in forums: 2 Months 9 h 47 m 28 sec
Reputation Power: 4080
Just do it something like this:
Code:
#!/usr/bin/python

import sys

file = '/etc/does_not_exist'

fo = None
try:
    fo = open(file)
except:
    print('No such file')
    sys.exit(0)
finally:
    if fo != None: fo.close()

print('Made it this far')

Note that I initialize fo (and set it to None) outside the try block so that it will be defined by the time it hits finally. Within the finally clause, I check to see if it is None or not and only close it if it is not None. This is similar to how the perl code does a:
Code:
close($fo) if defined($fo);
__________________
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne

Reply With Quote
  #3  
Old February 19th, 2013, 03:16 PM
SuperOscar SuperOscar is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2007
Location: Joensuu, Finland
Posts: 412 SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 7 h 14 m 58 sec
Reputation Power: 65
Quote:
Originally Posted by dkoleary
The books/tutorials that I've been reading suggest having a 'finally:' clause to the try/except to close the file.


I think that’s old information. The new correct way is to use “with”:

Code:
with open(file) as fo:
    # ...


I would check the existence of the file beforehand with os.path.isfile() but I guess wrapping the above in a try...except block is OK too.
__________________
My armada: openSUSE 12.3 (home desktop, laptop, work desktop), Ubuntu 12.04 LTS (mini laptop), Debian GNU/Linux 7.0 (server), Mythbuntu 12.04 LTS (HTPC), Bodhi Linux 2.0 & Windows 7 Ultimate (test desktop), FreeBSD 9.1 (test server)

Reply With Quote
  #4  
Old February 19th, 2013, 03:54 PM
dkoleary dkoleary is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2013
Posts: 11 dkoleary User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 h 45 m 47 sec
Reputation Power: 0
Hey;

Thank you both! Very helpful. With some reading on the 'with' keyword, I'm down to:

Code:
#### imports:
import sys

file = sys.argv[1]

try:
   with open(file) as fo:
      lines = fo.readlines()
except IOError as e:
   print "Can't open file:", e
   sys.exit(1)
   
print 'you made it this far!'


The idea of pre-initializing the variable is quite clever. Wish I'd thought of that myself!

Thanks again.

Doug O'Leary

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > File manipulation (try: except: finally:)

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap