Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

Easily find the next free file name

Project description

NextFreeFileName

NextFreeFileName is a micro-package aiming to simplify the process of finding the next available filename when generating files as part of a large process.

Overview

To understand the purpose of NextFreeFileName, walk thorough an exemplary case.
Let's suppose the following scenario:

  • You're generating SVG files using the contents of multiple JSON files
  • The filename of one of your processed JSON file is: performance_graph.json
  • You need to generate 3 SVG files using information from this JSON
  • You want all your generated SVGs to share a common name (usually the name of the source file)
  • You want to distinguish the generated SVGs by having a numeric suffix in their file names

To find the next free filename, you can execute the following statements:

from NextFreeFileName import NextFreeFileName

src_json = '/tmp/performance_graph.json'
svg_out = NextFreeFileName('/tmp/performance_graph.svg')

If /tmp/performance_graph.svg already exists, svg_out returns the following NextFreeFileName object:
PosixPath('/tmp/performance_graph_0.svg')
Otherwise the original path is returned with no numeric suffix: PosixPath('/tmp/performance_graph.svg').

File names can be dynamically generated using the NextFreeFileName.next() method.

Demo

To demonstrate a real-world use case, let's generate 4 empty .txt files:

from NextFreeFileName import NextFreeFileName

out_txt = NextFreeFileName('/tmp/performance_graph.txt')  # Can be str OR class 'pathlib.*'
i = 0
while i < 4:
    with open(out_txt.next(), 'w') as f:
        f.write('Some text...')
        f.close()
    i += 1

Results:

ls
# performance_graph.txt performance_graph_0.txt performance_graph_1.txt performance_graph_2.txt

API Description

class NextFreeFileName:
    def __init__(self,
                 file_path, glue="_", index=0, ignore_reserved=False, resolve_suffix=True, **kwargs):
        """
        Takes a path to a file and if already exists, a number gets appended to its end.
        If file exists, glue + index gets appended to it.
        If file does not exist, the initial value of file_path gets returned as Path.
        :param file_path: (str | Path) Path to existing or desired output
        :param glue: (str) Character gluing together the `original file name` and the `index`. Default=_ (underscore)
        :param index: (int) Number to start counting from
        :param ignore_reserved: Set to True if you don't want to compare glue's value to reserved character's list
        :param resolve_suffix: Sets index based on the file name's current numeric suffix (if exists)
        :keyword reserved_characters: (str[]): List of strings added to Reserved Characters
        """
  • To initialize NextFreeFileName, a value must be provided for file_path.
    Accepted types: str or a pathlib-like objects.
  • By default, filename and the generated integer are glued together with an underscore(_).
    To override it, set the value of glue to any valid unicode character. Exceptions: * / : < > ? \ | ".
  • By default, the generated integer starts at 0.
    To override it, set the value of index to any valid integer.
  • By default a few characters (see above) are restricted for glue.
    To disable this restriction, set ignore_reserved to True.

Reserved Characters

File systems have not always provided the same character set for composing a filename. Before Unicode became a de facto standard, file systems mostly used a locale-dependent character set. By contrast, some new systems permit a filename to be composed of almost any character of the Unicode repertoire, and even some non-Unicode byte sequences. Limitations may be imposed by the file system, operating system, application, or requirements for interoperability with other systems.
Many file system utilities prohibit control characters from appearing in filenames. In Unix-like file systems, the null character and the path separator / are prohibited.
File system utilities and naming conventions on Windows prohibit particular characters from appearing in filenames.

-- Filename#Reserved characters and words - Wikipedia

To achieve high cross-platform compatibility, the following characters are restricted by default:

@property
def _reserved_characters(self):
    return [
        '*',   # asterisk/star
        '/',   # slash
        ':',   # colon
        '<',   # less than
        '>',   # greater than
        '?',   # question mark
        '\\',  # backslash
        '|',   # vertical bar/pipe
        '"',   # quote
        *self._custom_reserved_characters
    ]

Parameters

  • To extend the list of reserved characters, use the reserved_characters kwarg when calling NextFreeFileName.
    reserved_characters must be list of strings type kwarg.
  • To disable the reserved character checking, set ignore_reserved to False when calling NextFreeFileName.

Installation

To install NFFN, execute the following steps:

  1. Get the latest Release or clone the repository:
    git clone git@github.com:theriverman/NextFreeFileName.git
  2. Install to your virtualenv by executing the following command:
    python setup.py install
  3. Import the main class to your project:
    from NFFN import NextFreeFileName

PyPI package may be added later.

Contributing/Packaging

To contribute, fork the repository, commit your changes and open a pull request.
This package is available at PyPI.

To release a new package over PyPI, issue the following commands:

  1. python3 setup.py sdist bdist_wheel
  2. python3 -m twine upload dist/*

Compatibility

Python 3.6.0 and above.

This library takes advantage of f-strings PEP 498 and Type Hints PEP 484.

Copyright

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for NextFreeFileName, version 0.0.2
Filename, size File type Python version Upload date Hashes
Filename, size NextFreeFileName-0.0.2-py3-none-any.whl (6.8 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size NextFreeFileName-0.0.2.tar.gz (5.0 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page