Member Avatar for Member #952511

Is it possible to make a Python program which checks if a file exists, maybe like:

#!/usr/bin/python

if exist 'File.txt':
  print "File.txt exists!"
else:
  print "File.txt does not exist :-("

Obviously the if exist code will fail, as it is not a python command, but is there anything like the above which works?

Dani AI

Generated

Nice thread. Building on , @MS, and : for modern Python 3, prefer either a simple, readable check with pathlib or, when you are about to use the file, rely on exceptions (EAFP) to avoid race conditions.

Quick existence check with pathlib (clear and cross-platform):

from pathlib import Path

p = Path("File.txt")
print("File.txt exists!" if p.is_file() else "File.txt does not exist :-(")

Creating a new file only if it does not already exist (atomic, no check-then-act bug):

try:
    with open("File.txt", "x"):
        pass  # created successfully
except FileExistsError:
    print("File.txt exists!")
else:
    print("Created File.txt")

Notes and gotchas:

  • If you actually need to read the file, follow ’s point and open it directly, catching specific errors like FileNotFoundError, PermissionError, or IsADirectoryError so your message explains the real problem.
  • Symlinks: Path.is_file() returns True for a symlink that points to a file. To flag a broken symlink, check p.is_symlink() and not p.exists().
  • Paths are relative to the current working directory. If you meant a file next to your script, use base = Path(__file__).resolve().parent and p = base / "File.txt".
  • Case matters on Linux/macOS but not on Windows, so File.txt and file.txt may be different files depending on the OS.

Recommended Answers

All 9 Replies

Look at os.path.exists and os.path.isfile thats dos what you describe.

>>> help(os.path.exists)
Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

>>> help(os.path.isfile)
Help on function isfile in module genericpath:

isfile(path)
    Test whether a path is a regular file

Or try/except that is a safe an pythonic way to solve this.

try:
   open()
except IOError as e:
   print 'No file found'
from os import path

PATH = "folder_path/file.txt"
if path.exists(PATH) and path.isfile(PATH):
    print "File does exist"
else:
      print "File doesn't exist!"
commented: best method +13

if path.exists(PATH) and path.isfile(PATH):

There is no extra value of using both only the latter is enough. But in multitasking conditions, the situation can change between execution of the test of condition and execution of the following statements as they are not 'atomic'. So it is considered more correct to react to missing file in try... except like snippsat showed last.

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = open(filename)
        f.close()
        return True
    except:
        return False

HiHe function is ok,but some changes that i think make it better.
Bare except(catch all maybe) i dont like this to much.
And with open() is preferred over open(),no need to close file object and it dos some error checking to.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

Or return the specific error masseage to user.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError as error:
        return 'A problem occurred: {}'.format(error)

Nice to use with, not sure when it was introduced? Earlier Python2 version don't have it.
A little simpler:

def file_exists2(filename):
    try:
        with open(filename): return True
    except:
        return False

The only thing you doing is to open a file, there are not too many error choices?

with, not sure when it was introduced?

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> dir(__future__)
['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_PRINT_FUNCTION', 'CO_FUTURE_UNICODE_LITERALS', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'print_function', 'unicode_literals', 'with_statement']
>>> print(__future__.with_statement)
_Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768)
>>> 

It was functioning with from __future__ import in version 2.5.0 and from 2.6.0 onwards it does not need import.

Nice to use with, not sure when it was introduced?

In python 2.5 september 19, 2006.

Bare "except:", with no exception specified is nasty because it can easily hide bugs.

except: #Dont do this

To use your code as example.

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = ope(filename) # misspelled "open"
        f.close()
        return True
    except:
        return False 

print file_exists('somefile.txt')

The misspelled "open" triggers a NameError,which is caught by the except clause.
So funcion return False,so it hide the real problem that there is NameError.
except IOError will only catch IOError and show that NameError is the problem.

When people see bare "except:" in code they can complain about it.

commented: I totally agree +13
Member Avatar for Member #952511

Hi again, guys.

Thanks for all your contributions; I really appreciate it, I got this to work at the end :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.