frazman
frazman

Reputation: 33293

Unable to write file in python

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

Answers (2)

unutbu
unutbu

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

Max E.
Max E.

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

Related Questions