Katalog-lista drzew w Pythonie

Jak uzyskać listę wszystkich plików (i katalogów) w danym katalogu w Pythonie?

Author: smci, 2008-09-23

20 answers

Jest to sposób na przemierzenie KAŻDEGO pliku i katalogu w drzewie katalogów:

import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')
 573
Author: Jerub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-17 16:54:50

Możesz użyć

os.listdir(path)

Dla odniesienia i więcej funkcji systemu operacyjnego spójrz tutaj:

 494
Author: rslite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-05 00:11:02

Oto funkcja pomocnicza, której używam dość często:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]
 87
Author: giltay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-23 13:23:29
import os

for filename in os.listdir("C:\\temp"):
    print  filename
 80
Author: curtisk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-03 17:28:51

Jeśli potrzebujesz zdolności globbingu, jest do tego moduł. Na przykład:

import glob
glob.glob('./[0-9].*')

Zwróci coś w stylu:

['./1.gif', './2.txt']

Zobacz dokumentację tutaj .

 12
Author: kenny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-24 20:58:14

Spróbuj tego:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)
 9
Author: paxdiablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-23 12:34:34

Dla plików w bieżącym katalogu roboczym bez podania ścieżki

Python 2.7:

import os
os.listdir(os.getcwd())

Python 3.x:

import os
os.listdir()

podziękowania dla Stam Kaly za komentarz do Pythona 3.x

 7
Author: Dave Engineer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-07 15:37:24

Implementacja rekurencyjna

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)
 4
Author: Arnaldo P. Figueira Figueira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-27 01:45:10

Napisałem długą wersję, ze wszystkimi opcjami, których mogę potrzebować: http://sam.nipl.net/code/python/find.py

Myślę, że tu też się zmieści:

#!/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:])
 2
Author: Sam Watkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-08 03:25:52

Ładny liner do listy tylko plików rekurencyjnie. Użyłem tego w moim setup.py dyrektywa package_data:

import os

[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]

Wiem, że to nie jest odpowiedź na pytanie, ale może się przydać

 1
Author: fivetentaylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-30 22:35:24

Dla Pythona 2

#!/bin/python2

import os

def scan_dir(path):
    print map(os.path.abspath, os.listdir(pwd))

Dla Pythona 3

Dla filtrów i map, należy je zawinąć list ()

#!/bin/python3

import os

def scan_dir(path):
    print(list(map(os.path.abspath, os.listdir(pwd))))

Zaleca się zastąpienie użycia map i filtrów wyrażeniami generatorów lub składaniem list:

#!/bin/python

import os

def scan_dir(path):
    print([os.path.abspath(f) for f in os.listdir(path)])
 1
Author: Alejandro Blasco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-14 10:11:03

Oto jednolinijkowa Wersja pytona:

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

Ten kod wyświetla pełną ścieżkę wszystkich plików i katalogów w podanej nazwie katalogu.

 1
Author: salehinejad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-21 16:31:10
#import modules
import os

_CURRENT_DIR = '.'


def rec_tree_traverse(curr_dir, indent):
    "recurcive function to traverse the directory"
    #print "[traverse_tree]"

    try :
        dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
    except:
        print "wrong path name/directory name"
        return

    for file_or_dir in dfList:

        if os.path.isdir(file_or_dir):
            #print "dir  : ",
            print indent, file_or_dir,"\\"
            rec_tree_traverse(file_or_dir, indent*2)

        if os.path.isfile(file_or_dir):
            #print "file : ",
            print indent, file_or_dir

    #end if for loop
#end of traverse_tree()

def main():

    base_dir = _CURRENT_DIR

    rec_tree_traverse(base_dir," ")

    raw_input("enter any key to exit....")
#end of main()


if __name__ == '__main__':
    main()
 0
Author: Alok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-23 11:56:34

FYI Dodaj filtr rozszerzenia lub pliku ext import os

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue
 0
Author: moylop260,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-19 18:26:01
import os, sys

#open files in directory

path = "My Documents"
dirs = os.listdir( path )

# print the files in given directory

for file in dirs:
   print (file)
 0
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-16 21:15:27

Gdybym pomyślał, że to wrzucę. Prosty i brudny sposób na wyszukiwanie wieloznaczne.

import re
import os

[a for a in os.listdir(".") if re.search("^.*\.py$",a)]
 0
Author: bng44270,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-25 13:31:56

Poniższy kod wyświetli listę katalogów i plików w katalogu

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)
 0
Author: Heenashree Khandelwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-21 05:15:15

Wiem, że to stare pytanie. To jest schludny sposób, na który natknąłem się, jeśli jesteś na maszynie liunx.

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
 0
Author: Abin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-09 21:04:19

Ten, który pracował ze mną, to jakby zmodyfikowana wersja z powyższej odpowiedzi.

Kod jest następujący:

"dir =' given_directory_name ' filenames = [os./ align = "left" / abspath (os./ align = "left" / join (dir,i)) dla i w os.listdir (dir)]"

 0
Author: Hassan3571619,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-18 16:29:26

Oto inna opcja.

os.scandir(path='.')

Zwraca iterator systemu operacyjnego.Obiekty DirEntry odpowiadające wpisom (wraz z informacją o atrybutach pliku) w katalogu podanym przez path.

przykład:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)

Użycie scandir () zamiast listdir () może znacznie zwiększyć wydajność kodu, który wymaga również informacji o typie pliku lub atrybutach pliku, ponieważ system operacyjny.Obiekty DirEntry ujawniają te informacje, jeśli system operacyjny udostępnia je, gdy skanowanie katalogu. Wszystkie os.Metody DirEntry mogą wykonywać wywołanie systemowe, ale is_dir() i is_file () zwykle wymagają wywołania systemowego tylko dla dowiązań symbolicznych; os.DirEntry.stat () zawsze wymaga wywołania systemowego w systemie Unix, ale wymaga tylko jednego dla dowiązań symbolicznych w systemie Windows.

Python Docs

 0
Author: Khaino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 08:31:31