Click here to Skip to main content
15,886,781 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

What I have tried:

import csv

with open('BTMA1.gro') as text_file, open('BTMA2.gro', 'w') as revised_file:
reader = csv.reader(text_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:]
writer.writerow(row)
Posted
Updated 3-Jun-21 8:04am
Comments
Richard MacCutchan 3-Jun-21 14:39pm    
Don't do this. If you make a mistake while writing the update then all your data can be lost.

1 solution

You can't read and write the same file to insert anything - that won't work because you can't insert into a file, just overwrite content. So your insert attempt would overwrite the next information you tried to read.

What you need to do is read the file up to the insert point while writing it out to the output file, write the inserted data, then write the rest of the input file to the output.
Then close both files, delete the input file, and rename the output.
 
Share this answer
 
Comments
mohammad rezayani 3-Jun-21 15:29pm    
Thank you very much. I added

os.remove('BTMA1.gro') # deleted original
os.rename('BTMA2.gro', 'BTMA1.gro') #renames new to original name

at the end of my code and is done.
OriginalGriff 3-Jun-21 15:33pm    
You're welcome - but I'd actually rename the input as a .BAK file instead of deleting it, just in case of "c**k-up syndrome"! :laugh:
mohammad rezayani 5-Jun-21 4:04am    
Thank you very much for your suggestion:).
OriginalGriff 5-Jun-21 4:44am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900