in-place


Namein-place JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/jwodder/inplace
SummaryIn-place file processing
upload_time2023-10-12 22:25:41
maintainer
docs_urlNone
authorJohn Thorvald Wodder II
requires_python>=3.8
licenseMIT
keywords inplace in-place io open file tmpfile tempfile sed redirection fileinput
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. image:: http://www.repostatus.org/badges/latest/active.svg
    :target: http://www.repostatus.org/#active
    :alt: Project Status: Active - The project has reached a stable, usable
          state and is being actively developed.

.. image:: https://github.com/jwodder/inplace/workflows/Test/badge.svg?branch=master
    :target: https://github.com/jwodder/inplace/actions?workflow=Test
    :alt: CI Status

.. image:: https://codecov.io/gh/jwodder/inplace/branch/master/graph/badge.svg
    :target: https://codecov.io/gh/jwodder/inplace

.. image:: https://img.shields.io/pypi/pyversions/in_place.svg
    :target: https://pypi.org/project/in_place

.. image:: https://img.shields.io/conda/vn/conda-forge/in_place.svg
    :target: https://anaconda.org/conda-forge/in_place
    :alt: Conda Version

.. image:: https://img.shields.io/github/license/jwodder/inplace.svg?maxAge=2592000
    :target: https://opensource.org/licenses/MIT
    :alt: MIT License

`GitHub <https://github.com/jwodder/inplace>`_
| `PyPI <https://pypi.org/project/in_place>`_
| `Issues <https://github.com/jwodder/inplace/issues>`_
| `Changelog <https://github.com/jwodder/inplace/blob/master/CHANGELOG.md>`_

The ``in_place`` module provides an ``InPlace`` class for reading & writing a
file "in-place": data that you write ends up at the same filepath that you read
from, and ``in_place`` takes care of all the necessary mucking about with
temporary files for you.

For example, given the file ``somefile.txt``::

    'Twas brillig, and the slithy toves
        Did gyre and gimble in the wabe;
    All mimsy were the borogoves,
        And the mome raths outgrabe.

and the program ``disemvowel.py``:

.. code:: python

    import in_place

    with in_place.InPlace("somefile.txt") as fp:
        for line in fp:
            fp.write("".join(c for c in line if c not in "AEIOUaeiou"))

after running the program, ``somefile.txt`` will have been edited in place,
reducing it to just::

    'Tws brllg, nd th slthy tvs
        Dd gyr nd gmbl n th wb;
    ll mmsy wr th brgvs,
        nd th mm rths tgrb.

and no sign of those pesky vowels remains!  If you want a sign of those pesky
vowels to remain, you can instead save the file's original contents in, say,
``somefile.txt~`` by constructing the filehandle with:

.. code:: python

    in_place.InPlace("somefile.txt", backup_ext="~")

or save to ``someotherfile.txt`` with:

.. code:: python

    in_place.InPlace("somefile.txt", backup="someotherfile.txt")

Compared to the in-place filtering implemented by the Python standard library's
|fileinput|_ module, ``in_place`` offers the following benefits:

- Instead of hijacking ``sys.stdout``, a new filehandle is returned for
  writing.
- The filehandle supports all of the standard I/O methods, not just
  ``readline()``.
- There are options for setting the encoding, encoding error handling, and
  newline policy for opening the file, along with support for opening files in
  binary mode, and these options apply to both input and output.
- The complete filename of the backup file can be specified; you aren't
  constrained to just adding an extension.
- When used as a context manager, ``in_place`` will restore the original file
  if an exception occurs.
- The creation of temporary files won't silently clobber innocent bystander
  files.

.. |fileinput| replace:: ``fileinput``
.. _fileinput: https://docs.python.org/3/library/fileinput.html


Installation
============
``in_place`` requires Python 3.8 or higher.  Just use `pip
<https://pip.pypa.io>`_ for Python 3 (You have pip, right?) to install it::

    python3 -m pip install in_place


Basic Usage
===========
``in_place`` provides a single class, ``InPlace``.  Its constructor takes the
following arguments:

``name=<PATH>`` (required)
   The path to the file to open & edit in-place

``mode=<"b"|"t"|None>``
   Whether to operate on the file in binary or text mode.  If ``mode`` is
   ``"b"``, the file will be opened in binary mode, and data will be read &
   written as ``bytes`` objects.  If ``mode`` is ``"t"`` or ``None`` (the
   default), the file will be opened in text mode, and data will be read &
   written as ``str`` objects.

``backup=<PATH>``
   If set, the original contents of the file will be saved to the given path
   when the instance is closed.  ``backup`` cannot be set to the empty string.

``backup_ext=<EXTENSION>``
   If set, the path to the backup file will be created by appending
   ``backup_ext`` to the original file path.

   ``backup`` and ``backup_ext`` are mutually exclusive.  ``backup_ext`` cannot
   be set to the empty string.

``**kwargs``
   Any additional keyword arguments (such as ``encoding``, ``errors``, and
   ``newline``) will be forwarded to ``open()`` when opening both the input and
   output file streams.

``name``, ``backup``, and ``backup_ext`` can be ``str``, filesystem-encoded
``bytes``, or path-like objects.

``InPlace`` instances act as read-write filehandles with the usual filehandle
attributes, specifically::

    __iter__()              __next__()              closed
    flush()                 name                    read()
    read1() *               readinto() *            readinto1() *
    readline()              readlines()             write()
    writelines()

    * binary mode only

``InPlace`` instances also feature the following new or modified attributes:

``close()``
   Close filehandles and move files to their final destinations.  If called
   after the filehandle has already been closed, ``close()`` does nothing.

   Be sure to always close your instances when you're done with them by calling
   ``close()`` or ``rollback()`` either explicitly or implicitly (i.e., via use
   as a context manager).

``rollback()``
   Like ``close()``, but discard the output data (keeping the original file
   intact) instead of replacing the original file with it

``__enter__()``, ``__exit__()``
   When an ``InPlace`` instance is used as a context manager, on exiting the
   context, the instance will be either closed (if all went well) or rolled
   back (if an exception occurred).  ``InPlace`` context managers are not
   reusable_ but are reentrant_ (as long as no further operations are performed
   after the innermost context ends).

``input``
   The actual filehandle that data is read from, in case you need to access it
   directly

``output``
   The actual filehandle that data is written to, in case you need to access it
   directly

.. _reentrant: https://docs.python.org/3/library/contextlib.html#reentrant-cms
.. _reusable: https://docs.python.org/3/library/contextlib.html#reusable-context-managers

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/jwodder/inplace",
    "name": "in-place",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "inplace,in-place,io,open,file,tmpfile,tempfile,sed,redirection,fileinput",
    "author": "John Thorvald Wodder II",
    "author_email": "inplace@varonathe.org",
    "download_url": "https://files.pythonhosted.org/packages/96/f5/aaaea4549a142d835ef0cb880ec0750b6136d07c5638b089c9de7128c375/in_place-1.0.0.tar.gz",
    "platform": null,
    "description": ".. image:: http://www.repostatus.org/badges/latest/active.svg\n    :target: http://www.repostatus.org/#active\n    :alt: Project Status: Active - The project has reached a stable, usable\n          state and is being actively developed.\n\n.. image:: https://github.com/jwodder/inplace/workflows/Test/badge.svg?branch=master\n    :target: https://github.com/jwodder/inplace/actions?workflow=Test\n    :alt: CI Status\n\n.. image:: https://codecov.io/gh/jwodder/inplace/branch/master/graph/badge.svg\n    :target: https://codecov.io/gh/jwodder/inplace\n\n.. image:: https://img.shields.io/pypi/pyversions/in_place.svg\n    :target: https://pypi.org/project/in_place\n\n.. image:: https://img.shields.io/conda/vn/conda-forge/in_place.svg\n    :target: https://anaconda.org/conda-forge/in_place\n    :alt: Conda Version\n\n.. image:: https://img.shields.io/github/license/jwodder/inplace.svg?maxAge=2592000\n    :target: https://opensource.org/licenses/MIT\n    :alt: MIT License\n\n`GitHub <https://github.com/jwodder/inplace>`_\n| `PyPI <https://pypi.org/project/in_place>`_\n| `Issues <https://github.com/jwodder/inplace/issues>`_\n| `Changelog <https://github.com/jwodder/inplace/blob/master/CHANGELOG.md>`_\n\nThe ``in_place`` module provides an ``InPlace`` class for reading & writing a\nfile \"in-place\": data that you write ends up at the same filepath that you read\nfrom, and ``in_place`` takes care of all the necessary mucking about with\ntemporary files for you.\n\nFor example, given the file ``somefile.txt``::\n\n    'Twas brillig, and the slithy toves\n        Did gyre and gimble in the wabe;\n    All mimsy were the borogoves,\n        And the mome raths outgrabe.\n\nand the program ``disemvowel.py``:\n\n.. code:: python\n\n    import in_place\n\n    with in_place.InPlace(\"somefile.txt\") as fp:\n        for line in fp:\n            fp.write(\"\".join(c for c in line if c not in \"AEIOUaeiou\"))\n\nafter running the program, ``somefile.txt`` will have been edited in place,\nreducing it to just::\n\n    'Tws brllg, nd th slthy tvs\n        Dd gyr nd gmbl n th wb;\n    ll mmsy wr th brgvs,\n        nd th mm rths tgrb.\n\nand no sign of those pesky vowels remains!  If you want a sign of those pesky\nvowels to remain, you can instead save the file's original contents in, say,\n``somefile.txt~`` by constructing the filehandle with:\n\n.. code:: python\n\n    in_place.InPlace(\"somefile.txt\", backup_ext=\"~\")\n\nor save to ``someotherfile.txt`` with:\n\n.. code:: python\n\n    in_place.InPlace(\"somefile.txt\", backup=\"someotherfile.txt\")\n\nCompared to the in-place filtering implemented by the Python standard library's\n|fileinput|_ module, ``in_place`` offers the following benefits:\n\n- Instead of hijacking ``sys.stdout``, a new filehandle is returned for\n  writing.\n- The filehandle supports all of the standard I/O methods, not just\n  ``readline()``.\n- There are options for setting the encoding, encoding error handling, and\n  newline policy for opening the file, along with support for opening files in\n  binary mode, and these options apply to both input and output.\n- The complete filename of the backup file can be specified; you aren't\n  constrained to just adding an extension.\n- When used as a context manager, ``in_place`` will restore the original file\n  if an exception occurs.\n- The creation of temporary files won't silently clobber innocent bystander\n  files.\n\n.. |fileinput| replace:: ``fileinput``\n.. _fileinput: https://docs.python.org/3/library/fileinput.html\n\n\nInstallation\n============\n``in_place`` requires Python 3.8 or higher.  Just use `pip\n<https://pip.pypa.io>`_ for Python 3 (You have pip, right?) to install it::\n\n    python3 -m pip install in_place\n\n\nBasic Usage\n===========\n``in_place`` provides a single class, ``InPlace``.  Its constructor takes the\nfollowing arguments:\n\n``name=<PATH>`` (required)\n   The path to the file to open & edit in-place\n\n``mode=<\"b\"|\"t\"|None>``\n   Whether to operate on the file in binary or text mode.  If ``mode`` is\n   ``\"b\"``, the file will be opened in binary mode, and data will be read &\n   written as ``bytes`` objects.  If ``mode`` is ``\"t\"`` or ``None`` (the\n   default), the file will be opened in text mode, and data will be read &\n   written as ``str`` objects.\n\n``backup=<PATH>``\n   If set, the original contents of the file will be saved to the given path\n   when the instance is closed.  ``backup`` cannot be set to the empty string.\n\n``backup_ext=<EXTENSION>``\n   If set, the path to the backup file will be created by appending\n   ``backup_ext`` to the original file path.\n\n   ``backup`` and ``backup_ext`` are mutually exclusive.  ``backup_ext`` cannot\n   be set to the empty string.\n\n``**kwargs``\n   Any additional keyword arguments (such as ``encoding``, ``errors``, and\n   ``newline``) will be forwarded to ``open()`` when opening both the input and\n   output file streams.\n\n``name``, ``backup``, and ``backup_ext`` can be ``str``, filesystem-encoded\n``bytes``, or path-like objects.\n\n``InPlace`` instances act as read-write filehandles with the usual filehandle\nattributes, specifically::\n\n    __iter__()              __next__()              closed\n    flush()                 name                    read()\n    read1() *               readinto() *            readinto1() *\n    readline()              readlines()             write()\n    writelines()\n\n    * binary mode only\n\n``InPlace`` instances also feature the following new or modified attributes:\n\n``close()``\n   Close filehandles and move files to their final destinations.  If called\n   after the filehandle has already been closed, ``close()`` does nothing.\n\n   Be sure to always close your instances when you're done with them by calling\n   ``close()`` or ``rollback()`` either explicitly or implicitly (i.e., via use\n   as a context manager).\n\n``rollback()``\n   Like ``close()``, but discard the output data (keeping the original file\n   intact) instead of replacing the original file with it\n\n``__enter__()``, ``__exit__()``\n   When an ``InPlace`` instance is used as a context manager, on exiting the\n   context, the instance will be either closed (if all went well) or rolled\n   back (if an exception occurred).  ``InPlace`` context managers are not\n   reusable_ but are reentrant_ (as long as no further operations are performed\n   after the innermost context ends).\n\n``input``\n   The actual filehandle that data is read from, in case you need to access it\n   directly\n\n``output``\n   The actual filehandle that data is written to, in case you need to access it\n   directly\n\n.. _reentrant: https://docs.python.org/3/library/contextlib.html#reentrant-cms\n.. _reusable: https://docs.python.org/3/library/contextlib.html#reusable-context-managers\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "In-place file processing",
    "version": "1.0.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/jwodder/inplace/issues",
        "Homepage": "https://github.com/jwodder/inplace",
        "Source Code": "https://github.com/jwodder/inplace"
    },
    "split_keywords": [
        "inplace",
        "in-place",
        "io",
        "open",
        "file",
        "tmpfile",
        "tempfile",
        "sed",
        "redirection",
        "fileinput"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d18aba8349aea1b22c4898e93fe57bb22d78be28a673a747de409f6e21646a0b",
                "md5": "04f6bd22fb3dc02abe7afa8c69dec17a",
                "sha256": "df6781ae341cd57b0894a2e56dc6f7b1daad1235550313c004686dd19eba7fcd"
            },
            "downloads": -1,
            "filename": "in_place-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "04f6bd22fb3dc02abe7afa8c69dec17a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 7914,
            "upload_time": "2023-10-12T22:25:40",
            "upload_time_iso_8601": "2023-10-12T22:25:40.268540Z",
            "url": "https://files.pythonhosted.org/packages/d1/8a/ba8349aea1b22c4898e93fe57bb22d78be28a673a747de409f6e21646a0b/in_place-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "96f5aaaea4549a142d835ef0cb880ec0750b6136d07c5638b089c9de7128c375",
                "md5": "fcb7b6a39beefebea14e256ab6913acb",
                "sha256": "503048e91e0736cb092787c8017dce1328a62421f8fb81c29d25854c355af5ac"
            },
            "downloads": -1,
            "filename": "in_place-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "fcb7b6a39beefebea14e256ab6913acb",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16633,
            "upload_time": "2023-10-12T22:25:41",
            "upload_time_iso_8601": "2023-10-12T22:25:41.594995Z",
            "url": "https://files.pythonhosted.org/packages/96/f5/aaaea4549a142d835ef0cb880ec0750b6136d07c5638b089c9de7128c375/in_place-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-12 22:25:41",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jwodder",
    "github_project": "inplace",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "in-place"
}
        
Elapsed time: 0.12309s