Try open files and exceptions

35 Views Asked by At
def abrir_archivo(nombre_archivo):
    try:
        archivo = open(nombre_archivo, 'r')
    except FileNotFoundError:
        print("El archivo no fue encontrado")
    except:
        print("Error desconocido")
    else:
        print("Abriendo exitosamente")
    finally:
        print("Finalizando ejecucion")

abrir_archivo(1)

When I run the program, the else line is executed and prints "Opening Successfully", this happens with the numbers 0, 1 and 2. My question is why? Isn't it supposed to give an error? When I pass 3 or -1 or any other number, it does print "Unknown error" (I speak Spanish, if something is not understood... google translate is guilty uu)

1

There are 1 best solutions below

0
blhsing On

This is because the open function accepts a file descriptor as the file argument when it's an integer, and per POSIX standards, 0, 1 and 2 correspond to the standard input, standard output and standard error, respectively:

with open(1, 'w') as stdout:
    stdout.write('foo') # outputs foo to standard output

You may programmatically obtain the file descriptor by calling the fileno method of the file object:

import sys

with open(sys.stdout.fileno(), 'w') as stdout:
    stdout.write('foo') # outputs foo to standard output

Other integer numbers may be accepted if it represents an open file descriptor.