Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file and then overwriting it in Python

I've been trying to read a file and then overwrite it with some updated data. I've tried doing it like this:

#Created filename.txt with some data
with open('filename.txt', 'r+') as f:
    data = f.read()
    new_data = process(data)  # data is being changed
    f.seek(0)
    f.write(new_data)

For some reason, it doesn't overwrite the file and the content of it stays the same.

like image 492
pystudent Avatar asked Feb 28 '16 06:02

pystudent


People also ask

How do you overwrite an existing file in Python?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.

How do I stop a file overwriting in Python?

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). Save this answer.

How do I overwrite a file?

If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.


1 Answers

Truncate the file after seeking to the front. That will remove all of the existing data.

>>> open('deleteme', 'w').write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
>>> f = open('deleteme', 'r+')
>>> f.read()
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
>>> f.seek(0)
>>> f.truncate()
>>> f.write('bbb')
>>> f.close()
>>> open('deleteme').read()
'bbb'
>>> 
like image 68
tdelaney Avatar answered Sep 28 '22 01:09

tdelaney