Master Lee
Master Lee

Reputation: 43

Why can't I use "r+" mode to create a new file in Python with open()

In the docs of the open() built-in function, the meaning of "+" is as follows:

open a disk file for updating (reading and writing)

But when I use open() to create a new file with python 3.5 in windows 7, I got a FileNotFoundError.

tmp_file=open(str(temp_path),'r+')

From the explanation of open() in the docs, wouldn't it create a new empty file if the file specified doesn't exist when using the r+ mode?

Upvotes: 4

Views: 3065

Answers (3)

Hasidul Islam
Hasidul Islam

Reputation: 416

You can see the full documentation of the built-in open function here. Short Description of the parameters So the + sign adds update functionality to an added parameter. It does not give you permission to create a new file. That is why you are getting the error.

Upvotes: 1

D4Vinci
D4Vinci

Reputation: 53

You should use :
file = open(str(temp_path), 'w+')

Upvotes: 0

Dekel
Dekel

Reputation: 62536

r+ mode will open an existing file for write, but will not create the file if it doesn't exists.

You should open the file with w if you want to create a new file.

Upvotes: 0

Related Questions