Related
How do I check if a directory exists?
Use os.path.isdir for directories only:
>>> import os
>>> os.path.isdir('new_folder')
True
Use os.path.exists for both files and directories:
>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
Alternatively, you can use pathlib:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False
Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir() and exists() methods of a Path object can be used to answer the question:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
Paths (and strings) can be joined together with the / operator:
In [5]: q = p / 'bin' / 'vim'
In [6]: q
Out[6]: PosixPath('/usr/bin/vim')
In [7]: q.exists()
Out[7]: True
In [8]: q.is_dir()
Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
So close! os.path.isdir returns True if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False.
Yes, use os.path.exists().
We can check with 2 built in functions
os.path.isdir("directory")
It will give boolean true the specified directory is available.
os.path.exists("directoryorfile")
It will give boolead true if specified directory or file is available.
To check whether the path is directory;
os.path.isdir("directorypath")
will give boolean true if the path is directory
Yes use os.path.isdir(path)
The following code checks the referred directory in your code exists or not, if it doesn't exist in your workplace then, it creates one:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
You may also want to create the directory if it's not there.
Source, if it's still there on SO.
=====================================================================
On Python ≥ 3.5, use pathlib.Path.mkdir:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try os.path.exists, and consider os.makedirs for the creation.
import os
if not os.path.exists(directory):
os.makedirs(directory)
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...) to be sure.
Just to provide the os.stat version (python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise
os provides you with a lot of these capabilities:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
the listdir will throw an exception if the input path is invalid.
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')
There is a convenient Unipath module.
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
Other related things you might need:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
You can install it using pip:
$ pip3 install unipath
It's similar to the built-in pathlib. The difference is that it treats every path as a string (Path is a subclass of the str), so if some function expects a string, you can easily pass it a Path object without a need to convert it to a string.
For example, this works great with Django and settings.py:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
Two things
check if the directory exist?
if not, create a directory (optional).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")
Step 1: Import the os.path module
import the os.path module before running the code.
import os.path
from os import path
Step 2: Use path.exists() function
The path.exists() method is used to find whether a file exists.
path.exists("your_file.txt")
Step 3: Use os.path.isfile()
We can use the isfile command to determine whether or not a given input is a file.
path.isfile('your_file.txt')
step 4: Use os.path.isdir()
We can use the os.path.dir() function to determine whether or not a given input is a directory.
path.isdir('myDirectory')
Here is the complete code
import os.path
from os import path
def main():
print ("File exists:"+str(path.exists('your_file.txt')))
print ("Directory exists:" + str(path.exists('myDirectory')))
print("Item is a file: " + str(path.isfile("your_file.txt")))
print("Item is a directory: " + str(path.isdir("myDirectory")))
if __name__== "__main__":
main()
pathlibPath.exists() For Python 3.4
Pathlib Module is included in Python 3.4 and later versions to handle file system paths. Python checks if a folder exists using an object-oriented technique.
import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
print ("File exist")
else:
print ("File not exist")
os.path.exists() – Returns True if path or directory does exists.
os.path.isfile() – Returns True if path is File.
os.path.isdir() – Returns True if path is Directory.
pathlib.Path.exists() – Returns True if path or directory does exists. (In Python 3.4 and above versions)
Article refered How do I check if directory exists in Python?
I'm using python 2.x and I don't know how to make my script randomly choose directories in the same PC to copy files. It's quite important because it is for my final project.Any help is appreciated.
You should have a look at tempfile package
In [1]: import tempfile
In [2]: print([f for f in dir(tempfile) if not f.startswith('_')])
['NamedTemporaryFile', 'SpooledTemporaryFile', 'TMP_MAX', 'TemporaryFile', 'gettempdir', 'gettempprefix', 'mkdtemp', 'mkstemp', 'mktemp', 'tempdir', 'template']
In [3]: help(tempfile.mkdtemp)
Help on function mkdtemp in module tempfile:
mkdtemp(suffix='', prefix='tmp', dir=None)
User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
Ok...I dont know where module x is, but I know that I need to get the path to the directory two levels up.
So, is there a more elegant way to do:
import os
two_up = os.path.dirname(os.path.dirname(__file__))
Solutions for both Python 2 and 3 are welcome!
You can use pathlib. Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI here. This should be easy to do using pip.
from pathlib import Path
p = Path(__file__).parents[1]
print(p)
# /absolute/path/to/two/levels/up
This uses the parents sequence which provides access to the parent directories and chooses the 2nd one up.
Note that p in this case will be some form of Path object, with their own methods. If you need the paths as string then you can call str on them.
Very easy:
Here is what you want:
import os.path as path
two_up = path.abspath(path.join(__file__ ,"../.."))
I was going to add this just to be silly, but also because it shows newcomers the potential usefulness of aliasing functions and/or imports.
Having written it, I think this code is more readable (i.e. lower time to grasp intention) than the other answers to date, and readability is (usually) king.
from os.path import dirname as up
two_up = up(up(__file__))
Note: you only want to do this kind of thing if your module is very small, or contextually cohesive.
The best solution (for python >= 3.4) when executing from any directory is:
from pathlib import Path
two_up = Path(__file__).resolve().parents[1]
For getting the directory 2 levels up:
import os.path as path
curr_dir=Path(os.path.dirname(os.path.abspath(__file__)))
two_dir_up_=os.fspath(Path(curr_dir.parent.parent).resolve())
I have done the following to go up two and drill down on other dir
default_config_dir=os.fspath(Path(curr_dir.parent.parent,
'data/config').resolve())
Personally, I find that using the os module is the easiest method as outlined below. If you are only going up one level, replace ('../..') with ('..').
import os
os.chdir('../..')
--Check:
os.getcwd()
More cross-platform implementation will be:
import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()
Using parent is not supported on Windows. Also need to add .resolve(), to:
Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)
(pathlib.Path('../../') ).resolve()
I have found that the following works well in 2.7.x
import os
two_up = os.path.normpath(os.path.join(__file__,'../'))
You can use this as a generic solution:
import os
def getParentDir(path, level=1):
return os.path.normpath( os.path.join(path, *([".."] * level)) )
Assuming you want to access folder named xzy two folders up your python file. This works for me and platform independent.
".././xyz"
100% working answer:
os.path.abspath(os.path.join(os.getcwd() ,"../.."))
There is already an accepted answer, but for two levels up I think a chaining approach is arguably more readable:
pathlib.Path(__file__).parent.parent.resolve()
Surprisingly it seems no one has yet explored this nice one-liner option:
import os
two_up = os.path.normpath(__file__).rsplit(os.sep, maxsplit=2)[0]
rsplit is interesting since the maxsplit parameter directly represents how many parent folders to move up and it always returns a result in just one pass through the path.
With Pathlib (recommended after Python 3.5, the/a general solution that works not only in file.py files, but also in Jupyter (or other kind of) notebook and Python shell is:
p = Path.cwd().resolve().parents[1]
You only need to substitute (__file__) for cwd() (current working directory).
Indeed it would even work just with:
p = Path().resolve().parents[1]
(and of course with .parent.parent instead of parents[1])
I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.
import os
grandparent_dir = os.path.abspath( # Convert into absolute path string
os.path.join( # Current file's grandparent directory
os.path.join( # Current file's parent directory
os.path.dirname( # Current file's directory
os.path.abspath(__file__) # Current file path
),
os.pardir
),
os.pardir
)
)
print grandparent_dir
And to prove it works, here I start out in ~/Documents/notes just so that I show the current directory doesn't influence outcome. I put the file grandpa.py with that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.
(testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py
/Users/alancoding/Documents/scripts/grandpa.py
(testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py
/Users/alancoding
This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.
I have a script, B.py, that is imported from another script, say A.py
If I import B in A, the __file__ magical constant, has converted some uppercase letters in its path to lowercase.
If I run B file directly, the __file__ constant HAS proper case regarding the path.
In short this is what happens. The following:
telplugins_path = os.path.dirname(os.path.realpath(__file__))
give me a path like this
C:\\Python\\lib\\site_packages\\mypackage
when it should be
C:\\Python\\Lib\\site_packages\\mypackage
Observe the change on 'Lib' -> 'lib'
Anyone have an idea on how to get the path to __file__ with proper case? Running this on Windows.
The windows file system is case-insensitive.
Python is just configured with the C:\Python\lib\site_packages path in the sys.path search list, so when you import your module, python constructs the filepath with the lowercase version.
This is not a problem. Windows will continue to load files using the lowercased version of the path.
On windows, the win32 module contain the function GetLongPathName. It does solve the above problem.
That is, the following gives a path with correct case:
aFile = win32api.GetLongPathName(__file__)
pathWithCorrectCase = os.path.split(aFile)[0]
However, I would like to avoid using the win32 module, since it seem not totally "standard".
Yields via standard library:
cased_path = glob.glob(re.sub(r'([^:])(?=[/\\]|$)', r'[\1]', __file__))[0]
There are certain calls you can make on windows that do fail with improper casing. There are also scenarios such as mine where these calls are being sent to a machiine that IS case sensitive.
Whatever the case may be, if you need proper casing on windows this is the best solution i have found.
For individual files, its easy enough to listdir, but if you have a directory path that you are not positive is properly cased:
import win32com.client as com
_dir = <your path>
fso = com.Dispat("Scripting.FileSystemObject")
folder = fso.GetFolder(_dir)
path = folder.path
This will return the properly cased path.
How do I check if a directory exists?
Use os.path.isdir for directories only:
>>> import os
>>> os.path.isdir('new_folder')
True
Use os.path.exists for both files and directories:
>>> import os
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
Alternatively, you can use pathlib:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False
Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir() and exists() methods of a Path object can be used to answer the question:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
Paths (and strings) can be joined together with the / operator:
In [5]: q = p / 'bin' / 'vim'
In [6]: q
Out[6]: PosixPath('/usr/bin/vim')
In [7]: q.exists()
Out[7]: True
In [8]: q.is_dir()
Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
So close! os.path.isdir returns True if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False.
Yes, use os.path.exists().
We can check with 2 built in functions
os.path.isdir("directory")
It will give boolean true the specified directory is available.
os.path.exists("directoryorfile")
It will give boolead true if specified directory or file is available.
To check whether the path is directory;
os.path.isdir("directorypath")
will give boolean true if the path is directory
Yes use os.path.isdir(path)
The following code checks the referred directory in your code exists or not, if it doesn't exist in your workplace then, it creates one:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
You may also want to create the directory if it's not there.
Source, if it's still there on SO.
=====================================================================
On Python ≥ 3.5, use pathlib.Path.mkdir:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try os.path.exists, and consider os.makedirs for the creation.
import os
if not os.path.exists(directory):
os.makedirs(directory)
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...) to be sure.
Just to provide the os.stat version (python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise
os provides you with a lot of these capabilities:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
the listdir will throw an exception if the input path is invalid.
#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')
There is a convenient Unipath module.
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
Other related things you might need:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
You can install it using pip:
$ pip3 install unipath
It's similar to the built-in pathlib. The difference is that it treats every path as a string (Path is a subclass of the str), so if some function expects a string, you can easily pass it a Path object without a need to convert it to a string.
For example, this works great with Django and settings.py:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
Two things
check if the directory exist?
if not, create a directory (optional).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")
Step 1: Import the os.path module
import the os.path module before running the code.
import os.path
from os import path
Step 2: Use path.exists() function
The path.exists() method is used to find whether a file exists.
path.exists("your_file.txt")
Step 3: Use os.path.isfile()
We can use the isfile command to determine whether or not a given input is a file.
path.isfile('your_file.txt')
step 4: Use os.path.isdir()
We can use the os.path.dir() function to determine whether or not a given input is a directory.
path.isdir('myDirectory')
Here is the complete code
import os.path
from os import path
def main():
print ("File exists:"+str(path.exists('your_file.txt')))
print ("Directory exists:" + str(path.exists('myDirectory')))
print("Item is a file: " + str(path.isfile("your_file.txt")))
print("Item is a directory: " + str(path.isdir("myDirectory")))
if __name__== "__main__":
main()
pathlibPath.exists() For Python 3.4
Pathlib Module is included in Python 3.4 and later versions to handle file system paths. Python checks if a folder exists using an object-oriented technique.
import pathlib
file = pathlib.Path("your_file.txt")
if file.exists ():
print ("File exist")
else:
print ("File not exist")
os.path.exists() – Returns True if path or directory does exists.
os.path.isfile() – Returns True if path is File.
os.path.isdir() – Returns True if path is Directory.
pathlib.Path.exists() – Returns True if path or directory does exists. (In Python 3.4 and above versions)
Article refered How do I check if directory exists in Python?