Reputation: 33293
Probably a very noob question..
But When I try:
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
I get an error
IOError: [Errno 2] No such file or directory: '/home/path/filename'
Isnt it that since i have said "w" .. it will write a new file if its not there already?
Upvotes: 2
Views: 180
Reputation: 880667
The error message can be reproduced like this:
import os
filename = '/home/path/filename'
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
f.close()
# IOError: [Errno 2] No such file or directory: '/home/path/filename'
The problem here is that filename
is an absolute path, so
os.path.join
ignores the first argument and returns filename
:
In [20]: filename = '/home/path/filename'
In [21]: os.path.join(os.path.dirname(__file__), filename)
Out[21]: '/home/path/filename'
Thus, you are specifying not only a file that does not exist, you are specifying a directory that does not exist. open
refuses to create the directory.
Upvotes: 3
Reputation: 1917
Are you trying to literally write home/path/filename
? In that case, it's complaining that /home/path
doesn't exist. Try creating a directory named /home/path
or choosing a file name inside a directory that already exists (for example, find out what the path is to your actual home directory.) You can also use relative paths. See
http://en.wikipedia.org/wiki/Path_%28computing%29
for the difference between absolute and relative paths.
Upvotes: 0