Python Forum

Full Version: How to save modification of a file in original file not a new one?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear all,

I have a code to modify a file. This code make changes on my file and save it to a new file. But, I want to have changes(modifications) on my original file not a new one. I made attempts to change the code but it didn't work. How can I modify my code to save modification on my original file? My code is attached here.

Thanks alot
The normal way is to write a temporary file, then move the temporary file to the original place in the file system.

Alternately, you can try the fileinput.FileInput class and its 'inplace' keyword argument to perform such tasks.
One way is to read/modify data from file to some datastructure (readlines?) and then move pointer to the beginning of file and write modified data back (writelines?). In order to do so file must be opened in 'r+' mode, something along those lines:

with open('my_file.txt', 'r+') as f:
    # read and modify data; readlines, iterating or something else
    f.seek(0)         
    # write back modified data
mjrezayani Wrote:But, I want to have changes(modifications) on my original file not a new one.
I have used in-place some times,It's easy to use
When using csv module most rewriter a little so it write like writerow(csv module).
Quick test.
# -*- coding: utf-8 -*-
"""
Created on Wed Jun  2 21:02:44 2021

@author: LENOVO
"""

import csv
from in_place import InPlace

with InPlace('csv_data.csv', encoding='utf-8', backup='otherfile.csv') as revised_file:
    reader = csv.reader(revised_file, delimiter=';')
    writer = csv.writer(revised_file, delimiter=';', quoting=0)
    for idx, row in enumerate(reader, start=1):
        if idx >= 3:
            row.insert(1, row[1][0])
            row[2] = row[2][1:]
        revised_file.write(f"{';'.join(row)}\n")
This line it's not needed anymore as it was in Python 2💀
# -*- coding: utf-8 -*-