Matthieu
Matthieu

Reputation: 437

Python read() not working

I'm trying to open a file, read the content, compare that with a hash and if necessary overwrite the file again. Should be basic stuff, but somehow I can't get it to work. I have now:

with open(name, 'wb+') as des:
    current_content = des.read()

I'm 100% sure the file is not empty, that I'm looking at the right file (later data gets written to it and that works) but somehow current_content ends up as an empty string.

with open(name, 'wb+') as des:
    des.write('Test')
    des.seek(0)
    current_content = des.read()

If I try the above current_content will return 'Test'. Anyone an idea what could cause this behaviour?

Upvotes: 1

Views: 3693

Answers (1)

Mitty
Mitty

Reputation: 340

Change the file reading option wb+ to ab+ and test it now. The problem is ab+ supports reading and appending the data(At EOF) in a binary file according to documentation. When you are using wb+ it may overwrite the existing file.

Upvotes: 1

Related Questions