Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3.4: Opening file with mode 'w' still gives me FileNotFound error [duplicate]

I'm having a small problem: while using the function open() with the 'w' mode, all documentation says that the file is created if it does not exist. Unfortunately, it appears that in my case, I get a FileNotFound error for some reason.

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

I receive the following error:

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

Any idea of why this might be? Thanks in advance!

EDIT: For those asking if the directory exists or not, I have made small changes to the code that might show you it is indeed the good path.

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: Disregard this question, problem solved. A second directory was being created after "example", thus it not working. Silly error.

like image 751
Balaam Avatar asked Aug 15 '15 11:08

Balaam


1 Answers

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

open() with 'w' only creates the non-existing file for you but not the whole directory path. So you first need to create the directories for the file.

like image 67
x squared Avatar answered Nov 01 '22 20:11

x squared