Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try/exception using isfile
#1
Hi,

I'm just wondering if it's possible to use an exception with isfile without opening it (ot course it/then/else do the job): just a reflexion

try:
    os.path.isfile(os.path.join(os.getcwd(), 'file.txt'))
    # open(os.path.join(os.getcwd(), 'file.txt'), 'r')
    
except FileNotFoundError:
    print("file not found")
Reply
#2
try:
    with open('file.txt', 'r') as f:
        print("file found")
except FileNotFoundError:
    print("file not found")
Reply
#3
Your code won't work as expected because os.path.isfile() doesn't raise a FileNotFoundError exception,
it simply returns True or False.
So for simple existence checks:
filepath = os.path.join(os.getcwd(), 'file.txt')
if os.path.isfile(filepath):
    # File exists
    pass
else:
    print("file not found")
Code over only check if File exists and raise exception for other errors,
A better appoch coud be using pathlib with exceptions (EAFP approach):
from pathlib import Path

path = Path.cwd() / "file.txt"
try:
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            print(line.rstrip())
except OSError as e:
    # Any OS-level I/O failure (missing file, perms, dir vs file, etc.)
    print(f"I/O error: {e}")
Or maybe give a own print messag for each error,to make it clearer.
from pathlib import Path

path = Path.cwd() / "file.txt"
try:
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            # do stuff with the line
            print(line.rstrip())
except FileNotFoundError:
    print(f"file not found: {path}")
except IsADirectoryError:
    print(f"path is a directory: {path}")
except PermissionError:
    print(f"no permission to read: {path}")
except OSError as e:
    # covers other I/O problems (e.g., too many open files, invalid name)
    print(f"I/O error: {e}")
Reply
#4
ok, my question is stupid: either we use the exception and we've to open the file, either with use isfile but without the exception: both cannot be used at the same time

Thanks
Reply
#5
Yes, Path.is_file() or os.path.isfile returns a boolean and won’t raise FileNotFoundError,
Ok for simple if/else test,not for exception-driven flow.
Simplest form.
from pathlib import Path

if (Path.cwd() / "file.txt").is_file():
    print("file found:")
else:
    print("file not found:")
If look at more complete exampes and read a little about LBYL vs EAFP.
look before you leap (LBYL)
from pathlib import Path

path = Path.cwd() / "file.txt"
if not path.exists():
    print("file not found")
elif path.is_dir():
    print("path is a directory")
else:
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            print(line.rstrip())
easier to ask forgiveness than permission (EAFP)
from pathlib import Path

path = Path.cwd() / "file.txt"
try:
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            print(line.rstrip())
except OSError as e:
    # Any OS-level I/O failure (missing file, perms, dir vs file, etc.)
    print(f"I/O error: {e}")
Reply
#6
Checking whether a resource is the available, is the wrong approach.

Simple example:
  1. Your program checks whether a path is a file.
  2. Result: True.
  3. Another process deletes the file.
  4. Your program tries to open the file and then throws an exception.


Your program only knows whether it can open a file without errors when it tries to open the file.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  During handling of the above exception, another exception occurred Skaperen 7 32,786 Dec-21-2018, 10:58 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020