The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Check If A File Exists In Python

TODO: Pull subtitle into page object

This is the way I check to see if a file exists at a given path in python:

code_start_default_section code_end_default_section
Results
File exists

#+OLDNOTES

TL:DR;

from pathlib import Path

my_file = Path("/path/to/file") if my_file.is_file(): # file exists

# oneliner:

if Path("/path/to/file").is_file() print('file exists.)

For dir:

.is_dir()

Exists in general:

.exists()

Via: https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions

--------------------------------------------------------------------------------

If the reason you're checking is so you can do something like `if file_exists: open_it()`, it's safer to use a `try` around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you're not planning to open the file immediately, you can use [`os.path.isfile`][1]

< Return `True` if path is an existing regular file. This follows symbolic links, so both [islink()][2] and [isfile()][1] can be true for the same path.

import os.path os.path.isfile(fname)

if you need to be sure it's a file.

Starting with Python 3.4, the [`pathlib` module][3] offers an object-oriented approach (backported to `pathlib2` in Python 2.7):

from pathlib import Path

my_file = Path("/path/to/file") if my_file.is_file(): # file exists

To check a directory, do:

if my_file.is_dir(): # directory exists

To check whether a `Path` object exists independently of whether is it a file or directory, use `exists()`:

if my_file.exists(): # path exists

You can also use `resolve(strict=True)` in a `try` block:

try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists

[1]:https://docs.python.org/2/library/os.path.html#os.path.isfile [2]:https://docs.python.org/2/library/os.path.html#os.path.islink [3]:https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Check If A File Exists In Python

-- p

This is the way I check to see if a file
exists at a given path in python:

-- code/
-- python

from pathlib import Path

check_file = "/Users/alan/Desktop/test.txt"
if Path(check_file).is_file():
    print("File exists")
else:
    print("File does not exist")

-- /code

-- results/

File does not exist

-- /results

-- p

** Alternatives

-- p

NOTE: These are still works in progress

-- p

Other related ways to do stuff

-- code/
-- python

from pathlib import Path

  check_file = Path("/Users/alan/Desktop/test.org")

  if check_file.is_file():
      print("File exists")
  else:
      print("File does not exist")

-- /code

-- results/

File exists

-- /results

-- p

#+OLDNOTES

-- p

TL:DR;

-- p

from pathlib import Path

-- p

my_file = Path("/path/to/file")
    if my_file.is_file():
        # file exists

-- p

# oneliner:

-- p

if Path("/path/to/file").is_file()
        print('file exists.)

-- p

For dir:

-- p

.is_dir()

-- p

Exists in general:

-- p

.exists()

-- p

Via: https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions

-- p

--------------------------------------------------------------------------------

-- p

If the reason you're checking is so you can do something like `if file_exists: open_it()`, it's safer to use a `try` around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

-- p

If you're not planning to open the file immediately, you can use [`os.path.isfile`][1]

-- p

> Return `True` if path is an existing regular file. This follows symbolic links, so both [islink()][2] and [isfile()][1] can be true for the same path.

-- p

import os.path
    os.path.isfile(fname)

-- p

if you need to be sure it's a file.

-- p

Starting with Python 3.4, the [`pathlib` module][3] offers an object-oriented approach (backported to `pathlib2` in Python 2.7):

-- p

from pathlib import Path

-- p

my_file = Path("/path/to/file")
    if my_file.is_file():
        # file exists

-- p

To check a directory, do:

-- p

if my_file.is_dir():
        # directory exists

-- p

To check whether a `Path` object exists independently of whether is it a file or directory, use `exists()`:

-- p

if my_file.exists():
        # path exists

-- p

You can also use `resolve(strict=True)` in a `try` block:

-- p

try:
        my_abs_path = my_file.resolve(strict=True)
    except FileNotFoundError:
        # doesn't exist
    else:
        # exists

-- p

[1]:https://docs.python.org/2/library/os.path.html#os.path.isfile
[2]:https://docs.python.org/2/library/os.path.html#os.path.islink
[3]:https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file


-- categories
-- Python

-- metadata
-- date: 2021-11-06 23:02:27
-- id: 20eogogq
-- status: draft
-- type: post
-- SCRUBBED_NEO: false
-- site: aws