FileNotFoundError: [Errno 2] No such file or directory: ''

Eryk Sun eryksun at gmail.com
Thu Apr 15 00:40:14 EDT 2021


On 4/14/21, Quentin Bock <qberz2005 at gmail.com> wrote:
>
> this is the only part of the code that causes the error
>
> file = open('Egils Saga 1-15.txt', "r")

Here's an app_abspath() function to resolve a filename against the
directory of the main script:

    import os
    import sys

    def get_main_file():
        if hasattr(sys, 'frozen'):
            return sys.executable
        main = getattr(sys.modules.get('__main__'), '__file__', '')
        return os.path.abspath(main) if main else ''

    def get_main_dir():
        return os.path.dirname(get_main_file()) or os.getcwd()

    def app_abspath(filename):
        return os.path.join(get_main_dir(), filename)

    file = open(app_abspath('Egils Saga 1-15.txt'), 'r')

In the frozen script case, sys.executable is the main 'script'. For a
"-c" command, there is no main file, so it uses the current working
directory.

Using the variable name "file" is fine so long as compatibility with
Python 2 isn't required. In Python 3, "file" is not a reserved keyword
and not the name of a builtin function or type.


More information about the Python-list mailing list