In-place file processing

1.0.1 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `in_place.InPlace` to read and write to a file, modifying its content in a transactional manner. It creates an example file, prints its original content, modifies a specific line using `in_place`, and then prints the updated content.

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())

view raw JSON →