[Python] Check if file is readable with Python: try or if/else?

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code:

    import glob, os
    for file in glob.glob("\\*.txt"):
    if os.access(file, os.R_OK):
    # Do something
    else:
    if not os.access(file, os.R_OK):
    print(file, "is not readable")
    else:
    print("Something went wrong with file/dir", file)
    break


    But I'm not entirely sure if this the right way to do it. Is it better to use try and catch the error? If so, how do I try for readability? Note the break in my else statement. As soon as a file can't be read I want to abort the loop.

    Continue reading...

Compartilhe esta Página