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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With