RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Accessing Files (r+ or w+)

Mon Apr 24, 2017 9:51 am

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).

User avatar
Paeryn
Posts: 2986
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Accessing Files (r+ or w+)

Mon Apr 24, 2017 10:52 am

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).
She who travels light — forgot something.

pcmanbob
Posts: 9611
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Accessing Files (r+ or w+)

Mon Apr 24, 2017 11:07 am

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.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Accessing Files (r+ or w+)

Mon Apr 24, 2017 12:42 pm

@Paeryn and pcmanbob
Thank you.

Return to “Python”