Directorio, subdirectorio y archivos de la lista de Python
Estoy tratando de hacer un script para listar todos los directorios, subdirectorios y archivos en un directorio dado.
Probé esto:
import sys,os
root = "/home/patate/directory/"
path = os.path.join(root, "targetdirectory")
for r,d,f in os.walk(path):
for file in f:
print os.path.join(root,file)
Desafortunadamente no funciona correctamente.
Tengo todos los archivos, pero no sus rutas completas.
Por ejemplo si la estructura dir sería:
/home/patate/directory/targetdirectory/123/456/789/file.txt
Se imprimiría:
/home/patate/directory/targetdirectory/file.txt
Lo que necesito es el primer resultado. Cualquier ayuda sería muy apreciada! Gracias.
6 answers
Use os.path.join
para concatenar el directorio y el nombre del archivo :
for path, subdirs, files in os.walk(root):
for name in files:
print os.path.join(path, name)
Tenga en cuenta el uso de path
y no root
en la concatenación, ya que usar root
sería incorrecto.
En Python 3.4, se agregó el módulo pathlib para facilitar las manipulaciones de rutas. Así que el equivalente a os.path.join
sería:
pathlib.PurePath(path, name)
La ventaja de pathlib
es que puede utilizar una variedad de métodos útiles en las rutas. Si utiliza la variante concreta Path
también puede hacer el sistema operativo real llama a través de ellos, como encadenar en un directorio, eliminar la ruta, abrir el archivo al que apunta y mucho más.
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
2013-11-24 18:24:00
Por si acaso... Obtener todos los archivos del directorio y subdirectorios que coincidan con algún patrón (*. py por ejemplo):
import os
from fnmatch import fnmatch
root = '/some/directory'
pattern = "*.py"
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch(name, pattern):
print os.path.join(path, name)
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-11-04 00:38:36
Aquí hay una sola línea:
import os
[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text
El bucle más externo val for sublist in ...
aplana la lista para que sea unidimensional. El bucle j
recopila una lista de cada nombre base de archivo y lo une a la ruta actual. Finalmente, el bucle i
itera sobre todos los directorios y subdirectorios.
Este ejemplo utiliza la ruta codificada ./
en el os.walk(...)
llame, puede complementar cualquier cadena de ruta que desee.
Nota: os.path.expanduser
y/o os.path.expandvars
puede ser utilizado para rutas cadenas como ~/
Extendiendo este ejemplo:
Es fácil de agregar en las pruebas de nombre de base de archivo y las pruebas de nombre de director.
Por Ejemplo, probando archivos *.jpg
:
... for j in i[2] if j.endswith('.jpg')] ...
Además, excluyendo el directorio .git
:
... for i in os.walk('./') if '.git' not in i[0].split('/')]
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-05-20 16:15:16
Debes usar 'r' en tu join en lugar de 'root'
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-05-26 03:46:56
Puedes echar un vistazo a esta muestra que hice. Utiliza el sistema operativo.camino.caminar función que está en desuso tenga cuidado.Usa una lista para almacenar todas las rutas de archivo
root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
'''
checks files in names'''
pat = "*" + ext[0]
for f in names:
if fnmatch.fnmatch(f,pat):
ext[1].append(os.path.join(dirname,f))
def writeTo(fList):
with open(where_to,"w") as f:
for di_r in fList:
f.write(di_r + "\n")
if __name__ == '__main__':
li = []
os.path.walk(root,fileWalker,[ex,li])
writeTo(li)
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
2013-05-04 23:02:22
Un poco más simple:
import os
from itertools import product, chain
chain.from_iterable([["\\".join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])
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
2018-02-21 08:49:48