Question

I need to do a try block on open but I want my variable to be available externally:

inputFile = null #This is the line that I don't know how to write
try:
    inputFile = open( sys.argv[0] )
except IOError as e:
    print "ERROR: Could not open " + sys.argv[0]

#use inputFile here
Was it helpful?

Solution

You don't need to declare the variable, Python uses function scope. A variable declared in the try block will automatically be available afterwards if the assignment was executed without any exception:

Case 1: No Exception

try:
    inputFile = open( sys.argv[0] )
except IOError as e:
    print "ERROR: Could not open " + sys.argv[0]
# inputFile is opened file

Case 2: Exception

try:
    inputFile = open( sys.argv[0] )
except IOError as e:
    print "ERROR: Could not open " + sys.argv[0]
# inputFile is not defined

OTHER TIPS

Use with.

try:
    with open(sys.argv[0]) as f:
        # operate on the file
except IOError as e:
    # handle the exception
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top