-3

There are various modes in a file which include read, write,append etc. r+ and w+ are also among them. But what is the difference between them?

I was trying to play around with various modes in files in python. But I couldn't get the difference between r+ and w+.

  • The official Python docs explain this, as do many online tutorials. Here's one that spells out all of the open modes nicely: https://www.geeksforgeeks.org/reading-writing-text-files-python/ – CryptoFool Dec 06 '22 at 18:23

1 Answers1

0

r+ does not truncate the file on opening; w+ does.

And though you didn't ask, but for completeness, r+ and a+ both open a file for reading and writing without truncating, but r+ leaves the file pointer at the beginning of the file, while a+ leaves the file pointer at the end of the file.

Further, as pointed out by @CryptoFool in a comment, r+ will not create a file if it does not already exist.

chepner
  • 497,756
  • 71
  • 530
  • 681