Python3.4: opening a file with 'w' mode still gives me a FileNotFound error

I have a small problem: when using the open() function with the 'w' mode, all the documentation says that the file is created if it does not exist. Unfortunately, it seems that in my case I am getting a FileNotFound error for some reason.

 with open(newFileName, 'w') as newFile: #CODE 

I get the following error:

 FileNotFoundError: [Errno 2] No such file or directory: 'path of file I have specified' 

Any idea why this could be? Thank you in advance!

EDIT: for those who ask if the directory exists or not, I made some small changes to the code, which can show you that this is a really good way.

 if not os.path.exists("example"): os.makedirs("example") BASE_DIR = os.path.dirname(os.path.abspath(__file__)) newFileName = "example/restOfPath" newFileName = os.path.join(BASE_DIR,newFileName) with open(newFileName, 'w') as newFile: 

I still get the following error:

 FileNotFoundError: [Errno 2] No such file or directory: 'correctPathToDirectory/example/restOfPath' 

EDIT2: ignore this question, the problem is resolved. After the “example”, a second directory is created, so it does not work. Stupid mistake.

+5
source share
1 answer

The reason for this error may be that the directory containing your new file does not yet exist.

open() with 'w' creates only a nonexistent file, but not the entire directory path. So first you need to create directories for the file.

+9
source

All Articles