open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
- Make sure the file exists: use
os.listdir()
to see the list of files in the current working directory - Make sure you're in the directory you think you're in with
os.getcwd()
(if you launch your code from an IDE, you may well be in a different directory) - You can then either:
- Call
os.chdir(dir)
,dir
being the folder where the file is
located, then open the file with just its name like you were doing. - Specify an absolute path to the file in your
open
call.
- Call
- Remember to use a raw string if your path uses backslashes, like
so:dir = r'C:\Python32'
- If you don't use raw-string, you have to escape every backslash:
'C:\\User\\Bob\\...'
- Forward-slashes also work on Windows
'C:/Python32'
and do not need to be escaped.
- If you don't use raw-string, you have to escape every backslash:
Let me clarify how Python finds files:
- An absolute path is a path that starts with your computer's root directory, for example
C:\Python\scripts
if you're on Windows. - A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the working directory. You can view Python's current working directory by calling
os.getcwd()
.
If you try to do open('sortedLists.yaml')
, Python will see that you are passing it a relative path, so it will search for the file inside the current working directory.
Calling os.chdir()
will change the current working directory.
Example: Let's say file.txt
is found in C:\Folder
.
To open it, you can do:
os.chdir(r'C:\Folder')
open('file.txt') # relative path, looks inside the current working directory
or
open(r'C:\Folder\file.txt') # absolute path
Getting error: FileNotFoundError: [Errno 2] No such file or directory when using Python open()
You can use glob, i.e.:
from glob import glob
p = "/path/to/*.txt"
for t in glob(p):
with open(t) as f:
text = f.read()
# do something with text
Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist
You are correct in surmising that the parent directory for the file must exist in order for open
to succeed. The simple way to deal with this is to make a call to os.makedirs
.
From the documentation:
os.makedirs(path[, mode])
Recursive directory creation function. Like
mkdir()
, but makes all intermediate-level directories needed to contain the leaf directory.
So your code might run something like this:
filename = ...
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filename, 'w'):
...
open file in w mode: IOError: [Errno 2] No such file or directory
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")
Related Topics
Python Multiprocessing Pool Hangs At Join
Valueerror: X and Y Must Be the Same Size
Convert the String 2.90K to 2900 or 5.2M to 5200000 in Pandas Dataframe
How to Use and Print the Pandas Dataframe Name
_Corrupt_Record Error When Reading a Json File into Spark
How to Calculate a Gaussian Kernel Matrix Efficiently in Numpy
Pandas Open_Excel() Fails With Xlrd.Biffh.Xlrderror: Can't Find Workbook in Ole2 Compound Document
Print 5 Items in a Row on Separate Lines for a List
How to Iterate Through a Matrix Column in Python
Python Does Not Match Format '%Y-%M-%Dt%H:%M:%S%Z.%F'
Animate a Rotating 3D Graph in Matplotlib
Loading All Images Using Imread from a Given Folder
Python Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:748)
Python - Remove Any Element from a List of Strings That Is a Substring of Another Element
Best Practices for Adding .Gitignore File for Python Projects
Insert Comma into Text File Using Python