79

When I try to open a file in write mode with the following code:

packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")

I get the following error:

IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'

The w mode should create the file if it doesn't exist, right? So how can this error ever occur?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
lugte098
  • 2,271
  • 5
  • 21
  • 30

7 Answers7

91

You'll see this error if the directory containing the file you're trying to open does not exist, even when trying to open the file in w mode.

Since you're opening the file with a relative path, it's possible that you're confused about exactly what that directory is. Try putting a quick print to check:

import os

curpath = os.path.abspath(os.curdir)
packet_file = "%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file")
print "Current path is: %s" % (curpath)
print "Trying to open: %s" % (os.path.join(curpath, packet_file))

packetFile = open(packet_file, "w")
Neuron
  • 5,141
  • 5
  • 38
  • 59
Lee
  • 2,204
  • 13
  • 15
21

Since you don't have a 'starting' slash, your python script is looking for this file relative to the current working directory (and not to the root of the filesystem). Also note that the directories leading up to the file must exist!

And: use os.path.join to combine elements of a path.

e.g.: os.path.join("dir", "dir2", "dir3", "myfile.ext")

Neuron
  • 5,141
  • 5
  • 38
  • 59
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
16

I had the same error, but in my case the cause was, under Windows, a path longer than ~250 characters.

Antonio
  • 19,451
  • 13
  • 99
  • 197
2

Check that that the script has write permissions on that directory. Try this:

chmod a+w dir/dir2/dir3

Note that this will give write permissions to everyone on that directory.

Felix
  • 88,392
  • 43
  • 149
  • 167
  • 4
    -1; this isn't a possible cause of the OP's error. If you don't have write permissions to the directory, Python will give you `IOError: [Errno 13] Permission denied: 'testdir/foo'`, not a `No such file or directory` error. – Mark Amery Jan 06 '16 at 18:52
  • 1
    This is a possible cause, if by "permissions" you mean "Windows Controlled folder access". Lots of programs will unhelpfully give no-such-file errors in this case instead of more logical permission-denied errors. Search "controlled folder access" in start and find python.exe in block history. – tsbertalan Dec 21 '22 at 04:39
2

I had the same issue, but my root cause was different than anyone's here. Thought I'd share in case someone else ran into the same issue.

In my case, I had accidentally misplaced my parentheses on the 'with' line:

with (open(os.path.join(curpath, unique_name)), 'w') as fw:

Gave the following error (modified to obscure company details and for clarity):

Traceback (most recent call last):
  File "./crap.py", line 60, in uniquify
    with (open(os.path.join(curpath, unique_name)), 'w') as fw:
IOError: [Errno 2] No such file or directory: '/<mypath>/bin/python/<filename>'

These parentheses put the 'w' with the with() function, not with open() as intended. I'm surprised it gives this IO Error, which implies it's something wrong with the open() call, which made this much harder to track down than if it obviously came from the with() call.

I didn't believe these results but just modified it again to replicate, and yes, I get the same error.

When I switch parentheses to the correct version:

with (open(os.path.join(curpath, unique_name), 'w')) as fw:

it works as intended.

Joel Wigton
  • 642
  • 6
  • 15
  • You get an IO error because the problem is in fact within the `open()` call, as that is the one that doesn't get the correct arguments. `with` is perfectly fine, as you are just passing it a tuple. To be clear: you don't need parenthesis with `with`, as it's not a method but a statement. When you do use parenthesis with multiple elements, it will get parsed as a tuple. – RobbertC5 Jan 06 '20 at 11:40
1

Similar issue happened in windows environment. Solution was to add "C:" to absolute path. My goal was to save some files in user Desktop

file_path = os.path.join(os.environ["HOMEPATH"], os.path.join("Desktop", 
    "log_file.log_%s_%s" %(
    strftime("%Y_%m_%d", localtime()), "number_1")))

then I was trying to open this directory to save such as

file_ref = open(file_path, "w")

I added this in order to run

file_ref = open(("C:\\"+file_path), "w")
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
MSK
  • 41
  • 3
1

This error will also occur if you are trying to overwrite a broken soft link to a file with the same name. In that case, delete the broken soft link and you will be able to write the new file.

abruin
  • 81
  • 2
  • In my case, on Windows, the file I was trying to create was a restricted filename, "Com2.mp4" -- I guess MS-DOS restricts special names, and it can give this error. https://answers.microsoft.com/en-us/windows/forum/all/unable-to-rename-a-folder-to-com-errorthe/ff48c793-ab97-4881-952a-df195321c11c – Ryan S Apr 15 '23 at 04:02