2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@unutbu.. How do i resolve this? What i was thinking of achieving was.. no matter from where i execute the code.. the file will be saved in the right location on server?
@Fraz: Try defining filename = 'filename' rather than an absolute path. That will cause os.path.join(..., filename) to place the file in the same directory as the script.
0

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.

1 Comment

HI. .Thanks for looking into my query.. home/path is there.. but just the filename is not there? thats what i am trying to write??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.