Reputation: 1
I am trying to create a file in a subdirectory, both of which will not exist when the program is first run. When I do this:
newfile = open('abc.txt','w')
It will create abc.txt just fine but the following will cause an error, saying the file or directory does not exist
newfile = open('folder/abc.txt','w')
I tried using os.makedirs to create the directory first but that failed as well raising the same error. What is the best way to create both the folder and file?
Thanks
Upvotes: 0
Views: 67
Reputation: 18128
A couple of things to check:
os.makedirs
takes just the path, not the file. I assume you know this already, but you haven't shown your call to makedirs
so I thought I'd mention it.
Consider passing an absolute, not a relative, path to makedirs
. Alternatively, use os.chdir
first, to change to a directory in which you know you have write permission.
Hope those help!
Upvotes: 0
Reputation: 11915
>>> import os
>>> os.makedirs('folder')
>>> newfile = open('folder' + os.sep + 'abc.txt', 'w')
>>> newfile.close()
>>> os.listdir('folder')
['abc.txt']
This works for me
Upvotes: 1