Come controllate se un file è un file normale o una directory usando Python?
Come controllate se un file è un file normale o una directory usando Python?
Risposte:
os.path.isdir()e os.path.isfile()dovrebbe darti quello che vuoi. Vedi:
http://docs.python.org/library/os.path.html
Come hanno già detto altre risposte, os.path.isdir()e os.path.isfile()sono quello che vuoi. Tuttavia, è necessario tenere presente che questi non sono gli unici due casi. Utilizzare os.path.islink()ad esempio per i collegamenti simbolici. Inoltre, tutti restituiscono Falsese il file non esiste, quindi probabilmente vorrai verificare anche con os.path.exists().
Python 3.4 ha introdotto il pathlibmodulo nella libreria standard, che fornisce un approccio orientato agli oggetti per gestire i percorsi del filesystem. I metodi rilevanti sarebbero .is_file()e .is_dir():
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.is_file()
Out[3]: False
In [4]: p.is_dir()
Out[4]: True
In [5]: q = p / 'bin' / 'vim'
In [6]: q.is_file()
Out[6]: True
In [7]: q.is_dir()
Out[7]: False
Pathlib è disponibile anche su Python 2.7 tramite il modulo pathlib2 su PyPi.
import os
if os.path.isdir(d):
print "dir"
else:
print "file"
Se stai solo attraversando una serie di directory, potresti essere meglio solo provare a os.chdirdare un errore / avviso se fallisce:
import os,sys
for DirName in sys.argv[1:]:
SaveDir = os.getcwd()
try:
os.chdir(DirName)
print "Changed to "+DirName
# Do some stuff here in the directory
os.chdir(SaveDir)
except:
sys.stderr.write("%s: WARNING: Cannot change to %s\n" % (sys.argv[0],DirName))