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
in_place takes care of all the necessary mucking about with
temporary files for you.
For example, given the file
'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
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:
or save to
Compared to the in-place filtering implemented by the Python standard library's
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
- 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_placewill restore the original file if an exception occurs.
- The creation of temporary files won't silently clobber innocent bystander files.
Just use pip (You have pip, right?) to install
pip install in_place
in_place provides a single class,
InPlace. Its constructor takes the
- The path to the file to open & edit in-place
- Whether to operate on the file in binary or text mode. If
'b', the file will be opened in binary mode, and data will be read & written as
str(Python 2) or
bytes(Python 3) objects. If
't', the file will be opened in text mode, and data will be read & written as
unicode(Python 2) or
str(Python 3) objects. If
None(the default), the file will be opened with
openusing the default mode, and data will be read & written as
strobjects, whatever those happen to be in your version of Python.
- If set, the original contents of the file will be saved to the given path when the instance is closed.
If set, the path to the backup file will be created by appending
backup_extto the original file path.
backup_extare mutually exclusive.
backup_extcannot be set to the empty string.
- By default, the instance is opened (including creating temporary files and
so forth) as soon as it's created. Setting
delay_open=Truedisables this; the instance must then be opened either via the
open()method or by using it as a context manager.
True, move the input file to a temporary location first and create the output file in its place (à la
fileinput) rather than the default behavior of creating the output file at a temporary location and only moving things around once
close()is called (à la GNU
- Any additional keyword arguments (such as
newline) will be forwarded to
io.open()(or the builtin
None) when opening both the input and output file strems.
backup_ext can be either
bytes in Python 3, and in Python 3.6 or later, path-like
objects are also accepted.
Earlier versions of this library provided separate
InPlaceBytesclasses for operating in text and binary mode. As of version 0.4.0, these classes are deprecated and will be removed in a future version. Code written for earlier versions should be updated to use
modeargument instead:InPlaceText(name, ...) -> InPlace(name, 't', ...) InPlaceBytes(name, ...) -> InPlace(name, 'b', ...)
InPlace instances act as filehandles with the usual filehandle
__iter__() close() closed flush() name read() readall() * readinto() * readline() readlines() write() writelines() * binary mode only
InPlace instances also feature the following new or modified attributes:
- Open the instance, creating filehandles for reading & writing. This method
must be called first before any of the other I/O methods can be used. It is
normally called automatically upon instance initialization unless
delay_openwas set to
ValueErroris raised if this method is called more than once in an instance's lifetime.
Close filehandles and move files to their final destinations. If called after the filhandle has already been closed,
Be sure to always close your instances when you're done with them by calling
rollback()either explicity or implicitly (i.e., via use as a context manager).
close(), but discard the output data (keeping the original file intact) instead of replacing the original file with it
- When an
InPlaceinstance is used as a context manager, it will be opened (if not open already) on entering and either closed (if all went well) or rolled back (if an exception occurred) on exiting.
InPlacecontext managers are not reusable but are reentrant (as long as no further operations are performed after the innermost context ends).
- The actual filehandle that data is read from, in case you need to access it directly
- The actual filehandle that data is written to, in case you need to access it directly