in_place module in Python
Sometimes, while working with Python files, we can have utility in which we wish to alter files without using system context or sys stdout. Such situation require reading/writing files inplace, i.e without using process resources. This can be achieved using the ein_place module in Python. This module –
- Doesn’t use sys.stdout, rather returns the new filehandler instance.
- Supports all filehandler methods.
- In case of exception, the original file is retained, helping in atomicity.
- Creation of temporary files doesn’t hit other files opened.
Simply run this command to install the required module
pip install in_place
Now to actually get the job done use in_place() method of this module.
in_place.InPlace(filename, mode=t, backup=None, backup_ext=None, delay_open=False, move_first=False)
filename : Location of file to open and edit inplace.
mode : Mode with which to open file. Options are byte (b) and text(t). In case its open in byte more, read and write happens in bytes. In text mode, R & W happens in string. Defaults to text mode.
backup : Path to save original file after the end of process in case to keep backup of original file.
backup_ext : Created backup of with name – filename + backup_ext, of original file before editing.
delay_open : In case set to True, it will only open file after calling open(), whereas by default its open as soon as class is initiated.
move_first : If set to True, the input file is sent to temporary location and output is edited in place first. By default this process takes place after calling of close() or when process ends.
Using this function the file in use is first opened and a required task is performed on it. Given below is the simplest implementation for the same.
Example 1 :
It is also possible to first back up the data of the existing file onto some other file and then make the required changes to the file. For this the name of the file by which you want to create a back-up is given as an value to backup argument.
Example 2 :
The alternative to the above method is the use for keyword backup_ext. Onto this just pass the extra word to differentiate the existing file from.
Please Login to comment...