pystudent
pystudent

Reputation: 571

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.

Upvotes: 16

Views: 9341

Answers (2)

Forge
Forge

Reputation: 6834

You should add a call to truncate after seek as tdelaney suggested.

Try reading and writing in different scopes, the code is more clear that way and the data processing is not done when the file handlers are open.

data = ''
with open('filename.txt', 'r') as f:
    data = f.read()

new_data = process(data)  
with open('filename.txt', 'w+') as f:
    f.write(new_data)

Upvotes: 2

tdelaney
tdelaney

Reputation: 77337

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'
>>> 

Upvotes: 14

Related Questions