web-dev-qa-db-fra.com

Comment trouver si le répertoire existe dans Python

Dans le module os de Python, existe-t-il un moyen de rechercher un répertoire, comme par exemple:

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
992
David542

Vous recherchez os.path.isdir , ou os.path.exists si vous ne vous souciez pas de savoir s'il s'agit d'un fichier ou d'un répertoire.

Exemple:

_import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
_
1546
phihag

Si proche! os.path.isdir renvoie True si vous transmettez le nom d'un répertoire existant. S'il n'existe pas ou s'il ne s'agit pas d'un répertoire, il retourne False.

70
Kirk Strauser

Python 3.4 a introduit module pathlib dans la bibliothèque standard, qui fournit une approche orientée objet pour gérer les chemins du système de fichiers:

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

In [5]: q = p / 'bin' / 'vim'

In [6]: q.exists()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

Pathlib est également disponible sur Python 2.7 via le module pathlib2 sur PyPi.

46
joelostblom

Oui, utilisez os.path.exists() .

32
aganders3

Nous pouvons vérifier avec 2 fonctions intégrées

os.path.isdir("directory")

Cela donnera à boolean true que le répertoire spécifié est disponible.

os.path.exists("directoryorfile")

Boolead sera vrai si le répertoire ou le fichier spécifié est disponible.

Pour vérifier si le chemin est un répertoire;

os.path.isdir("directorypath")

donnera boolean true si le chemin est directory

17
Vivek Ananthan

Oui, utilisez os.path.isdir (path)

16
RanRag

Un péché:

In [3]: os.path.exists('/d/temp')
Out[3]: True

Probablement ajouter une os.path.isdir(...) pour en être sûr.

10
AlG

Juste pour fournir la version os.stat (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
8
Tyler A.

os vous fournit beaucoup de ces capacités:

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

le listdir lève une exception si le chemin d'entrée est invalide.

7
dputros
#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')
5
JoboFive

Il existe un module pratique Unipath .

>>> from unipath import Path 
>>>  
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True

Autres choses connexes dont vous pourriez avoir besoin:

>>> 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

Vous pouvez l'installer en utilisant pip:

$ pip3 install unipath

C'est similaire au pathlib intégré. La différence réside dans le fait qu'il traite chaque chemin comme une chaîne (Path est une sous-classe de str). Ainsi, si une fonction attend une chaîne, vous pouvez facilement lui passer un objet Path sans qu'il soit nécessaire de la convertir en chaîne.

Par exemple, cela fonctionne très bien avec Django et settings.py:

# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
2
Max Malysh