Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
check if file exists.
#4
Don't ask for permission ask for forgiveness.

Instead of checking every possible possibility, you should use try: except:


import sys


filename = 'not_existing_file'

try:
    fd = open(filename)
except OSError as e:
    print(e, file=sys.stderr)
    sys.exit(1)
Or you can be more concrete:

filename = '/dev/mem'

try:
    fd = open(filename)
except PermissionError as e:
    print('You don\'t have the permission to open the file {}'.format(filename), file=sys.stderr)
    sys.exit(1)
except OSError as e:
    # PermissionError is a subclass of OSError
    # First you should be very concrete, and later
    # you can catch all other Errors
    # NEVER USE except:
    # this will catch all Errors
    print(e, file=sys.stderr)
    sys.exit(2)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
check if file exists. - by ian - Jul-14-2017, 04:28 PM
RE: check if file exists. - by ichabod801 - Jul-14-2017, 04:53 PM
RE: check if file exists. - by ian - Jul-14-2017, 05:22 PM
RE: check if file exists. - by DeaD_EyE - Jul-14-2017, 08:22 PM
RE: check if file exists. - by snippsat - Jul-14-2017, 09:09 PM
RE: check if file exists. - by ichabod801 - Jul-14-2017, 10:35 PM
RE: check if file exists. - by wavic - Jul-15-2017, 09:34 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  please check this i wanna use a csv file as a graph xCj11 5 1,515 Aug-25-2022, 08:19 PM
Last Post: deanhystad
  check if a file exist on the internet and get the size kucingkembar 6 1,823 Apr-16-2022, 05:09 PM
Last Post: kucingkembar
  Code to check folder and sub folders for new file and alert fioranosnake 2 1,961 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Check last time file was accessed Pavel_47 4 2,855 Jun-01-2021, 05:47 PM
Last Post: Yoriz
  How to check if a file has finished being written leocsmith 2 7,891 Apr-14-2021, 04:21 PM
Last Post: perfringo
  pathlib destpath.exists() true even file does not exist NaN 9 4,731 Dec-01-2020, 12:43 PM
Last Post: NaN
  Check if a file exists. Pedroski55 5 3,335 Sep-08-2020, 10:01 AM
Last Post: Pedroski55
  How to check to see a dbf file is EOF ? DarkCoder2020 0 1,738 Jun-16-2020, 05:03 PM
Last Post: DarkCoder2020
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,186 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  Building a script to check size of file upon creation mightyn00b 2 2,400 Apr-04-2020, 04:39 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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