Come identificare se un file è normale file o directory usando Python


129

Come controllate se un file è un file normale o una directory usando Python?

Risposte:



36

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().


10

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.



2

os.path.isdir('string')
os.path.isfile('string')


2

prova questo:

import os.path
if os.path.isdir("path/to/your/file"):
    print "it's a directory"
else:
    print "it's a file"

-1

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))
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.