-1

I have two functions to see if a file exists, I am wondering which one of them is considered the most Pythonic, A, B or none? Is it a good practice to always use exceptions?

import os.path
from os import path

# Method A
def file_exists_A(file):

    try:
        with open(file, 'r') as f:
            print("Method A: file exists")
    except Exception as e:
        print('Method A: file not found\n')

# Method B
def file_exists_B(file):

    try:
        if path.exists(file):
            print("Method B: file exists")
    except Exception as e:
        print("Method B: file not found\n")

file_exists_A("file.txt")
#file_exists_B("file.txt")
Andre
  • 598
  • 1
  • 7
  • 18

1 Answers1

3

I am a big fan of pathlib.

from pathlib import Path

if Path(filename).exists():
    print("It is there")
else:
    print("It is not there")
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28