How to check file existence using Python?

Small tutorial with code examples and video about how to check if file exists in Python
10 August 2017   2429

There are several Python methods to check does a file exist.

1. os.path.isfile
It returns True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path

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

2. Starting with Python 3.4, the pathlib module 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

3. To check a directory, use:

if my_file.is_dir():
    # directory exists

4. 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() in a try block:

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

OpenAI to Create Fake News Creating Algorithm

On the basis of one or two phrases that set the theme, it is able to “write” a fairly plausible story
18 February 2019   132

The GPT-2 algorithm, created by OpenAI for working with language and texts, turned out to be a master in creating fake news. On the basis of one or two phrases that set the theme, it is able to “compose” a fairly plausible story. For example:

  • an article about scientists who have found a herd of unicorns in the Andes;
  • news about pop star Miley Cyrus caught on shoplifting;
  • artistic text about Legolas and Gimli attacking the orcs;
  • an essay on how waste recycling harms the economy, nature, and human health.

The developers did not publish the source code of the model entirely, fearing abuse by unscrupulous users. For fellow researchers, they posted on GitHub a simplified version of the algorithm and gave a link to the preprint of the scientific article. The overall results are published on the OpenAI blog.

GPT-2 is a general purpose algorithm. The developers taught it to answer questions, “understand” the logic of a text, a sentence, finish building phrases. In this case, the algorithm worked worse than the model of a specific purpose. Researchers suggest that the indicators can be improved by expanding the training datasets and choosing computers more efficiently.