Wie erhalte ich eine Liste aller Dateien (und Verzeichnisse) in einem bestimmten Verzeichnis in Python?
Antworten
Zu viele Anzeigen?
Sam Watkins
Punkte
7162
Ich habe eine lange Version geschrieben, mit allen Optionen, die ich brauchen könnte: http://sam.nipl.net/code/python/find.py
Ich denke, es wird auch hier passen:
#!/usr/bin/env python
import os
import sys
def ls(dir, hidden=False, relative=True):
nodes = []
for nm in os.listdir(dir):
if not hidden and nm.startswith('.'):
continue
if not relative:
nm = os.path.join(dir, nm)
nodes.append(nm)
nodes.sort()
return nodes
def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
root = os.path.join(root, '') # add slash if not there
for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
if relative:
parent = parent[len(root):]
if dirs and parent:
yield os.path.join(parent, '')
if not hidden:
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
if files:
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
def test(root):
print "* directory listing, with hidden files:"
print ls(root, hidden=True)
print
print "* recursive listing, with dirs, but no hidden files:"
for f in find(root, dirs=True):
print f
print
if __name__ == "__main__":
test(*sys.argv[1:])
HassanSh__3571619
Punkte
1409
fivetentaylor
Punkte
1227
Alejandro Blasco
Punkte
1074
Für Python 2
#!/bin/python2
import os
def scan_dir(path):
print map(os.path.abspath, os.listdir(pwd))
Für Python 3
Für filter und map müssen Sie sie mit list() einschließen
#!/bin/python3
import os
def scan_dir(path):
print(list(map(os.path.abspath, os.listdir(pwd))))
Die Empfehlung lautet nun, dass Sie Ihre Verwendung von map und filter durch Generatorenausdrücke oder List Comprehensions ersetzen:
#!/bin/python
import os
def scan_dir(path):
print([os.path.abspath(f) for f in os.listdir(path)])
Heenashree Khandelwal
Punkte
621
2 Stimmen
Rekursiv oder nicht? Bitte klären Sie das. Für nicht rekursive Lösungen siehe: stackoverflow.com/questions/973473/