[Python] How to safely check whether a Fortran file exists when reading it with Python?

Discussão em 'Python' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I need to read in Python a file written in Fortran. To do this, I'm using numpy's f2py. Basically, I write a parse.f90 file:

    subroutine read_params(filename, params)
    implicit none
    ! Argument Declarations !
    character(len=*), intent(in) :: filename
    integer, dimension(4), intent(out) :: params
    ! Variable Declarations
    integer :: i

    open (unit=1,status="unknown",file=filename,form="unformatted")
    rewind 1
    read(1) (params(i), i=1, 4)

    end subroutine read_params


    Then I compile it with

    python -m numpy.f2py -c -m parse parse.f90


    And now I can import it in my Python script:

    from pathlib import Path
    import numpy as np
    from .parse import read_params

    def do_stuff_with_params(path: Path):
    params = read_params(path)
    # do something with the parameters
    return


    Now, my issue is that sometimes the Fortran file may not exist, for example because the user of do_stuff_with_params passed it the wrong path. Since however path is not a Python file object, the usual with open trick doesn't apply. So far, I used the following workaround:

    def do_stuff_with_params(path: Path):
    if not path.exists():
    raise FileNotFoundError(f'{path} does not exist ')
    params = read_params(path)
    # do something with the parameters
    return


    But this isn't ideal for the usual reasons (the file may be moved or deleted between the if check and when it's actually opened). Also, I actually need to read the file twice because of Fortran limitations (long story...), so I would have to add two if statements. How can I solve this? I was wondering if I could raise an exception in parse.f90 and pass it to the Python interpreter, but I don't know how to do it.

    Continue reading...

Compartilhe esta Página