Page 1 of 1

Accessing Files (r+ or w+)

Posted: Mon Apr 24, 2017 9:51 am
by RDS
I use the book by Mike McGrath - Python in Easy Steps.
I find this book is excellent and in it (on page 106) he describes the commands to open files and how to read or write.

file = open ('example.txt' , 'r+')
This command is described as "Open a text file to read from or write to"

file = open ('example.txt' , 'w+')
This command is described as "Open a text file to write to or read from"

Could someone please advise me what is the difference and when each one is used, as they seem to be the same to me (apart from the obvious).

Re: Accessing Files (r+ or w+)

Posted: Mon Apr 24, 2017 10:52 am
by Paeryn
r+ opens a file for reading and writing with the current position set at the start of the file (so you can read the original contents).

w+ opens a file for reading and writing (or creates one if it there was no file originally) and truncates it, that is the previous contents of an existing file will be deleted (so you can't read the original contents).

Re: Accessing Files (r+ or w+)

Posted: Mon Apr 24, 2017 11:07 am
by pcmanbob
There is also another option.
file = open ('example.txt' , 'a')
the a stands for append the file is opened for writing but at the end of the current contents so you can add to the file, it will also create a file if one does not exist.

Re: Accessing Files (r+ or w+)

Posted: Mon Apr 24, 2017 12:42 pm
by RDS
@Paeryn and pcmanbob
Thank you.