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:
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.
source share