operativo.camine sin excavar en los directorios a continuación


¿Cómo puedo limitar os.walk para que solo devuelva archivos en el directorio que le proporciono?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList
Author: Honest Abe, 2008-10-23

15 answers

Utilice la función walklevel.

import os

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

Funciona igual que os.walk, pero puede pasarle un parámetro level que indica cuán profunda será la recursión.

 78
Author: nosklo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-19 19:40:02

No use so.pie.

Ejemplo:

import os

root = "C:\\"
for item in os.listdir(root):
    if os.path.isfile(os.path.join(root, item)):
        print item
 171
Author: Yuval Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-23 10:30:34

Creo que la solución es realmente muy simple.

Use

break

Para hacer solo la primera iteración del bucle for, debe haber una forma más elegante.

for root, dirs, files in os.walk(dir_name):
    for f in files:
        ...
        ...
    break
...

La primera vez que llame al sistema operativo.walk, devuelve tulipanes para el directorio actual, luego en el siguiente bucle los contenidos del siguiente directorio.

Tome el script original y simplemente agregue un break.

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
        break
    return outputList
 29
Author: Pieter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-21 01:48:42

La sugerencia de usar listdir es buena. La respuesta directa a su pregunta es root, dirs, files = os.walk(dir_name).next()

 17
Author: Alex Coventry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-23 10:46:22

Si tiene requisitos más complejos que solo el directorio superior (por ejemplo, ignorar dirs de VCS, etc.), también puede modificar la lista de directorios para evitar el sistema operativo.camina recursivamente a través de ellos.

Ie:

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        dirs[:] = [d for d in dirs if is_good(d)]
        for f in files:
            do_stuff()

Nota - tenga cuidado de mutar la lista, en lugar de simplemente volver a enlazarla. Obviamente os.walk no sabe sobre el rebinding externo.

 9
Author: Brian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-29 09:59:01

Usted podría utilizar os.listdir() que devuelve una lista de nombres (tanto para archivos como para directorios) en un directorio dado. Si necesita distinguir entre archivos y directorios, llame a os.stat() en cada nombre.

 7
Author: Greg Hewgill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-23 10:06:02

La misma idea con listdir, pero más corto:

[f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]
 4
Author: Oleg Gryb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-22 12:32:52

En Python 3, pude hacer esto:

import os
dir = "/path/to/files/"

#List all files immediately under this folder:
print ( next( os.walk(dir) )[2] )

#List all folders immediately under this folder:
print ( next( os.walk(dir) )[1] )
 3
Author: Jay Sheth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-01 14:13:41
for path, dirs, files in os.walk('.'):
    print path, dirs, files
    del dirs[:] # go only one level deep
 3
Author: masterxilo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-03 15:43:13

Tenía ganas de tirar mis 2 peniques.

baselevel = len(rootdir.split("\\"))
for subdirs, dirs, files in os.walk(rootdir):
    curlevel = len(subdirs.split("\\"))
    if curlevel <= baselevel + 1:
        [do stuff]
 3
Author: Matt R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 08:14:38

También puedes hacer lo siguiente:

for path, subdirs, files in os.walk(dir_name):
    for name in files:
        if path == ".": #this will filter the files in the current directory
             #code here
 1
Author: Diana G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-18 23:15:07

Así es como lo resolví

if recursive:
    items = os.walk(target_directory)
else:
    items = [next(os.walk(target_directory))]

...
 0
Author: Deifyed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-06 17:59:14

Hay un problema cuando se usa listdir. Operativo.camino.isdir(identificador) debe ser una ruta absoluta. Para elegir subdirectorios que hacer:

for dirname in os.listdir(rootdir):
  if os.path.isdir(os.path.join(rootdir, dirname)):
     print("I got a subdirectory: %s" % dirname)

La alternativa es cambiar al directorio para hacer las pruebas sin el sistema operativo.camino.unir().

 0
Author: Kemin Zhou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-23 18:42:26

Puede usar este fragmento

for root, dirs, files in os.walk(directory):
    if level > 0:
        # do some stuff
    else:
        break
    level-=1
 0
Author: RousseauAlexandre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-24 08:56:51

Crear una lista de exclusiones, utilizar fnmatch para saltar la estructura de directorios y hacer el proceso

excludes= ['a\*\b', 'c\d\e']
for root, directories, files in os.walk('Start_Folder'):
    if not any(fnmatch.fnmatch(nf_root, pattern) for pattern in excludes):
        for root, directories, files in os.walk(nf_root):
            ....
            do the process
            ....

Igual que para "incluye":

if **any**(fnmatch.fnmatch(nf_root, pattern) for pattern in **includes**):
 0
Author: Hamsavardhini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 09:49:23