In-place file processing
The `in-place` library provides an `InPlace` class for robust and convenient in-place editing of files. It handles temporary files, encoding, and error management, simplifying common tasks like filtering or transforming file contents without needing to manually manage temporary files or worry about data loss during unexpected interruptions. The current version is 1.0.1 and it is actively maintained with a focus on stability and compatibility.
Warnings
- gotcha Unlike Python's standard `fileinput` module, `in-place` does not hijack `sys.stdout` for writing. Users coming from `fileinput` must explicitly call `fp.write()` to output modified lines, or `fp.write(line)` to preserve unchanged lines, otherwise content will be lost.
- gotcha When using `in_place.InPlace` with the `backup_ext` argument, providing an empty string for the extension will raise an error. The library explicitly prevents this to avoid ambiguity.
- gotcha When working with binary files, remember to open `InPlace` in binary mode (`mode='b'`). Otherwise, the file will be opened in text mode (default `mode=None`), which can lead to unexpected encoding/decoding errors or corruption of non-textual data.
Install
-
pip install in-place
Imports
- InPlace
import in_place with in_place.InPlace('filename.txt') as fp:
Quickstart
import in_place
# Create a dummy file for demonstration
with open('example.txt', 'w') as f:
f.write('Line 1\n')
f.write('Line 2 to be modified\n')
f.write('Line 3\n')
print('Original file content:')
with open('example.txt', 'r') as f:
print(f.read())
# Modify 'example.txt' in-place: change 'Line 2' to 'Modified Line 2'
with in_place.InPlace('example.txt') as fp:
for line in fp:
if 'Line 2' in line:
fp.write(line.replace('Line 2', 'Modified Line 2'))
else:
fp.write(line)
print('\nModified file content:')
with open('example.txt', 'r') as f:
print(f.read())