Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which mode recreate, writes and reads while opening a file in python?

My understanding of the the documentation is that w writes and truncates first while + updates (reads and writes):

f=open("/tmp/f",mode="tw+")
f.write("foo\nbar")
f.readlines() #returns empty list? What am I missing?

https://docs.python.org/3/library/functions.html#open

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Mode r+ will read/write without truncating and w+ will read/write with truncating first.

What you’re missing is the fact that after writing, your file position is at the end of the file. If you’ll use f.seek(0) after writing, you’ll be able to read just fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading