การใช้ os.walk () เพื่อสำรวจไดเรกทอรีซ้ำใน Python


151

ฉันต้องการนำทางจากไดเรกทอรีรากไปยังไดเรกทอรีอื่นทั้งหมดภายในและพิมพ์เดียวกัน

นี่คือรหัสของฉัน:

#!/usr/bin/python

import os
import fnmatch

for root, dir, files in os.walk("."):
        print root
        print ""
        for items in fnmatch.filter(files, "*"):
                print "..." + items
        print ""

และนี่คือ O / P ของฉัน:

.

...Python_Notes
...pypy.py
...pypy.py.save
...classdemo.py
....goutputstream-J9ZUXW
...latest.py
...pack.py
...classdemo.pyc
...Python_Notes~
...module-demo.py
...filetype.py

./packagedemo

...classdemo.py
...__init__.pyc
...__init__.py
...classdemo.pyc

ด้านบน.และ./packagedemoเป็นไดเรกทอรี

อย่างไรก็ตามฉันต้องพิมพ์ O / P ด้วยวิธีต่อไปนี้:

A
---a.txt
---b.txt
---B
------c.out

ด้านบนAและBเป็นไดเรกทอรีและส่วนที่เหลือเป็นไฟล์


6
ฉันต้องการที่จะเพิ่มโพสต์เล็ก ๆ นี้ที่นี่เกี่ยวกับพลังของหลาม: >>> พิมพ์ 2 * '-' ----
Nitaai

คำตอบ:


228

สิ่งนี้จะให้ผลลัพธ์ที่ต้องการ

#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

6
path = os.path.relpath (root, basepath) .split (os.sep)
Semprini

9
@Ajay เป็นคนหวาดระแวงและทำos.walk(u".")เพราะเส้นทางสามารถเป็น Unicode ได้
Ciro Santilli 郝海东冠状病六四事件法轮功

3
ยังดีกว่าos.path.curdir
Jir

ฉันใช้ไปos.path.walkระยะหนึ่งแล้วos.walkมันก็ใหม่สำหรับฉัน! เด็ดถั่ว
Tom

@Semprini อะไรคือสิ่งที่basepathเท่ากับในรหัสของคุณ?
stelios

23

ลองนี้:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""FileTreeMaker.py: ..."""

__author__  = "legendmohe"

import os
import argparse
import time

class FileTreeMaker(object):

    def _recurse(self, parent_path, file_list, prefix, output_buf, level):
        if len(file_list) == 0 \
            or (self.max_level != -1 and self.max_level <= level):
            return
        else:
            file_list.sort(key=lambda f: os.path.isfile(os.path.join(parent_path, f)))
            for idx, sub_path in enumerate(file_list):
                if any(exclude_name in sub_path for exclude_name in self.exn):
                    continue

                full_path = os.path.join(parent_path, sub_path)
                idc = "┣━"
                if idx == len(file_list) - 1:
                    idc = "┗━"

                if os.path.isdir(full_path) and sub_path not in self.exf:
                    output_buf.append("%s%s[%s]" % (prefix, idc, sub_path))
                    if len(file_list) > 1 and idx != len(file_list) - 1:
                        tmp_prefix = prefix + "┃  "
                    else:
                        tmp_prefix = prefix + "    "
                    self._recurse(full_path, os.listdir(full_path), tmp_prefix, output_buf, level + 1)
                elif os.path.isfile(full_path):
                    output_buf.append("%s%s%s" % (prefix, idc, sub_path))

    def make(self, args):
        self.root = args.root
        self.exf = args.exclude_folder
        self.exn = args.exclude_name
        self.max_level = args.max_level

        print("root:%s" % self.root)

        buf = []
        path_parts = self.root.rsplit(os.path.sep, 1)
        buf.append("[%s]" % (path_parts[-1],))
        self._recurse(self.root, os.listdir(self.root), "", buf, 0)

        output_str = "\n".join(buf)
        if len(args.output) != 0:
            with open(args.output, 'w') as of:
                of.write(output_str)
        return output_str

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--root", help="root of file tree", default=".")
    parser.add_argument("-o", "--output", help="output file name", default="")
    parser.add_argument("-xf", "--exclude_folder", nargs='*', help="exclude folder", default=[])
    parser.add_argument("-xn", "--exclude_name", nargs='*', help="exclude name", default=[])
    parser.add_argument("-m", "--max_level", help="max level",
                        type=int, default=-1)
    args = parser.parse_args()
    print(FileTreeMaker().make(args))

คุณจะได้รับสิ่งนี้:

root:.
[.]
┣━[.idea]
  ┣━[scopes]
    ┗━scope_settings.xml
  ┣━.name
  ┣━Demo.iml
  ┣━encodings.xml
  ┣━misc.xml
  ┣━modules.xml
  ┣━vcs.xml
  ┗━workspace.xml
┣━[test1]
  ┗━test1.txt
┣━[test2]
  ┣━[test2-2]
    ┗━[test2-3]
        ┣━test2
        ┗━test2-3-1
  ┗━test2
┣━folder_tree_maker.py
┗━tree.py

สวัสดีฉันรักบทของคุณจริงๆ แต่มันซับซ้อนเกินไปสำหรับโปรเจ็กต์ที่ฉันกำลังทำอยู่มีโอกาสที่ฉันจะได้มันเป็นฟังก์ชั่นเล็ก ๆ น้อย ๆ หรือไม่โดยมีอาร์กิวเมนต์ -r อยู่เท่านั้น?
jeff_h

วิธีการพิมพ์ใน. txt ฉันพยายามprint(FileTreeMaker().make(args),file=tree)แต่มันทำให้ฉัน'charmap' codec can't encode characters in position 17-21: character maps to <undefined>
หลุยส์เฟลิเป้

idc หมายถึงอะไร
เสียง

ผมเขียนสิ่งที่คล้ายกับos.listdir()เกินไป ของคุณดีกว่ามาก; ฉันไม่สามารถเรียกซ้ำข้อมูลได้มันทำงานได้แค่ 2 หรือ 3 ชั้นเท่านั้น ในตอนท้ายฉันตัดสินใจลองอีกครั้งตั้งแต่เริ่มต้นด้วยos.walk()ซึ่งฉันคิดว่าจะเหมาะสมกว่า ฉันประหลาดใจที่คุณไม่ได้ใช้เลย
เสียง

11

มีฟังก์ชั่นที่เหมาะสมกว่าสำหรับสิ่งนี้ในosแพ็คเกจ แต่ถ้าคุณต้องใช้os.walkนี่คือสิ่งที่ฉันคิดขึ้นมา

def walkdir(dirname):
    for cur, _dirs, files in os.walk(dirname):
        pref = ''
        head, tail = os.path.split(cur)
        while head:
            pref += '---'
            head, _tail = os.path.split(head)
        print(pref+tail)
        for f in files:
            print(pref+'---'+f)

เอาท์พุท:

>>> walkdir('.')
.
---file3
---file2
---my.py
---file1
---A
------file2
------file1
---B
------file3
------file2
------file4
------file1
---__pycache__
------my.cpython-33.pyc

5
ดังนั้นฟังก์ชั่นที่เหมาะสมกว่าคืออะไร? (ใน 3.5 หากมีความสำคัญ)
Al Lelopath

ขออภัยไม่มีโอกาสที่จะจำสิ่งที่ฉันหมายถึงโดยที่ เป็นไปได้ว่าฉันหมายถึงos.listdirแต่วิธีการแก้ปัญหาของ @ ajay นั้น
zaquest

5

คุณสามารถใช้os.walkและนั่นอาจเป็นวิธีที่ง่ายที่สุด แต่นี่เป็นแนวคิดในการสำรวจ:

import sys, os

FILES = False

def main():
    if len(sys.argv) > 2 and sys.argv[2].upper() == '/F':
        global FILES; FILES = True
    try:
        tree(sys.argv[1])
    except:
        print('Usage: {} <directory>'.format(os.path.basename(sys.argv[0])))

def tree(path):
    path = os.path.abspath(path)
    dirs, files = listdir(path)[:2]
    print(path)
    walk(path, dirs, files)
    if not dirs:
        print('No subfolders exist')

def walk(root, dirs, files, prefix=''):
    if FILES and files:
        file_prefix = prefix + ('|' if dirs else ' ') + '   '
        for name in files:
            print(file_prefix + name)
        print(file_prefix)
    dir_prefix, walk_prefix = prefix + '+---', prefix + '|   '
    for pos, neg, name in enumerate2(dirs):
        if neg == -1:
            dir_prefix, walk_prefix = prefix + '\\---', prefix + '    '
        print(dir_prefix + name)
        path = os.path.join(root, name)
        try:
            dirs, files = listdir(path)[:2]
        except:
            pass
        else:
            walk(path, dirs, files, walk_prefix)

def listdir(path):
    dirs, files, links = [], [], []
    for name in os.listdir(path):
        path_name = os.path.join(path, name)
        if os.path.isdir(path_name):
            dirs.append(name)
        elif os.path.isfile(path_name):
            files.append(name)
        elif os.path.islink(path_name):
            links.append(name)
    return dirs, files, links

def enumerate2(sequence):
    length = len(sequence)
    for count, value in enumerate(sequence):
        yield count, count - length, value

if __name__ == '__main__':
    main()

คุณอาจรู้จักเอกสารต่อไปนี้จากคำสั่ง TREE ใน terminal Windows:

Graphically displays the folder structure of a drive or path.

TREE [drive:][path] [/F] [/A]

   /F   Display the names of the files in each folder.
   /A   Use ASCII instead of extended characters.

5

เรียกซ้ำผ่านไดเรกทอรีที่คุณได้รับไฟล์ทั้งหมดจาก dirs ทั้งหมดในไดเรกทอรีปัจจุบันและคุณได้รับ dirs ทั้งหมดจากไดเรกทอรีปัจจุบัน - เพราะรหัสข้างต้นไม่มีความเรียบง่าย (imho):

for root, dirs, files in os.walk(rootFolderPath):
    for filename in files:
        doSomethingWithFile(os.path.join(root, filename))
    for dirname in dirs:
        doSomewthingWithDir(os.path.join(root, dirname))

3
คำตอบที่เป็นประโยชน์ที่สุด โปรดทราบว่าos.path.join(root, filename)ให้เส้นทางแบบเต็มไปยังไฟล์แม้ว่าไฟล์จะซ้อนในหลายไดเรกทอรี
clw

4

ใช้สำหรับชื่อโฟลเดอร์:

def printFolderName(init_indent, rootFolder):
    fname = rootFolder.split(os.sep)[-1]
    root_levels = rootFolder.count(os.sep)
    # os.walk treats dirs breadth-first, but files depth-first (go figure)
    for root, dirs, files in os.walk(rootFolder):
        # print the directories below the root
        levels = root.count(os.sep) - root_levels
        indent = ' '*(levels*2)
        print init_indent + indent + root.split(os.sep)[-1]

3
#!/usr/bin/python

import os 

def tracing(a):
    global i>
    for item in os.listdir(a):
        if os.path.isfile(item):
            print i + item 
        else:
            print i + item 
            i+=i
            tracing(item)

i = "---"
tracing(".")

1

ให้ชื่อโฟลเดอร์เดินผ่านลำดับชั้นทั้งหมดซ้ำ

#! /usr/local/bin/python3
# findLargeFiles.py - given a folder name, walk through its entire hierarchy
#                   - print folders and files within each folder

import os

def recursive_walk(folder):
    for folderName, subfolders, filenames in os.walk(folder):
        if subfolders:
            for subfolder in subfolders:
                recursive_walk(subfolder)
        print('\nFolder: ' + folderName + '\n')
        for filename in filenames:
            print(filename + '\n')

recursive_walk('/name/of/folder')

4
ไม่จำเป็นต้องเรียก os.walk ซ้ำ ๆ เพราะมันแบนการสอบถามซ้ำแล้ว นั่นคือเหตุผลที่มันส่งคืนอาร์กิวเมนต์ folderName
gwideman

1

จะเป็นวิธีที่ดีที่สุด

def traverse_dir_recur(dir):
    import os
    l = os.listdir(dir)
    for d in l:
        if os.path.isdir(dir + d):
            traverse_dir_recur(dir+  d +"/")
        else:
            print(dir + d)

ไม่ทำงานสำหรับฉันใน Python3 ฉันถือว่าข้อผิดพลาดเกิดขึ้นdir + dซึ่งอาจต่อกันได้โดยไม่มีตัวคั่นไดเรกทอรี น่าจะดีกว่าถ้าใช้os.path.joinสำหรับเชื่อมโยงไดเรกทอรีกับชื่อไฟล์
Zvika

0

ลองทำสิ่งนี้ ง่ายหนึ่ง

 #!/usr/bin/python
 import os
 # Creating an empty list that will contain the already traversed paths
 donePaths = []
 def direct(path):
       for paths,dirs,files in os.walk(path):
             if paths not in donePaths:
                    count = paths.count('/')
                    if files:
                          for ele1 in files:
                                print '---------' * (count), ele1
                    if dirs:
                          for ele2 in dirs:
                                print '---------' * (count), ele2
                                absPath = os.path.join(paths,ele2)
              # recursively calling the direct function on each directory
                                direct(absPath)
                   # adding the paths to the list that got traversed 
                                donePaths.append(absPath)

 path = raw_input("Enter any path to get the following Dir Tree ...\n")
 direct(path)

======== ส่งออกด้านล่าง ========

 /home/test
 ------------------ b.txt
 ------------------ a.txt
 ------------------ a
 --------------------------- a1.txt
 ------------------ b
 --------------------------- b1.txt
 --------------------------- b2.txt
 --------------------------- cde
 ------------------------------------ cde.txt
 ------------------------------------ cdeDir
 --------------------------------------------- cdeDir.txt
 ------------------ c
 --------------------------- c.txt
 --------------------------- c1
 ------------------------------------ c1.txt
 ------------------------------------ c2.txt

จุดตรวจสอบสำหรับเส้นทางที่ผ่านไปแล้วคืออะไร หากเป็นการตรวจจับลูปที่เกิดจากลิงก์แสดงว่าค่าเริ่มต้นของ OS.walk ไม่ใช่ลิงก์ที่ติดตาม มีสถานการณ์อื่นอีกไหม?
gwideman

0

ลองสิ่งนี้:

import os
root_name = next(os.walk("."))[0]
dir_names = next(os.walk("."))[1]
file_names = next(os.walk("."))[2]

ที่นี่ฉันคิดว่าเส้นทางของคุณเป็น "." ซึ่ง root_file และไดเร็กทอรีอื่นอยู่ที่นั่น ดังนั้นโดยทั่วไปเราแค่วนซ้ำทั่วต้นไม้โดยใช้การเรียก () ครั้งต่อไปเนื่องจาก os.walk ของเราเป็นเพียงฟังก์ชันการกำเนิดเท่านั้น ด้วยการทำเช่นนี้เราสามารถบันทึก Directory และชื่อไฟล์ทั้งหมดใน dir_names และ file_names ตามลำดับ


0

คุณสามารถเดินซ้ำ ๆ ในโฟลเดอร์และแสดงเนื้อหาทั้งหมดโดยใช้pathlib.Path ()

from pathlib import Path


def check_out_path(target_path, level=0):
    """"
    This function recursively prints all contents of a pathlib.Path object
    """
    def print_indented(folder, level):
        print('\t' * level + folder)

    print_indented(target_path.name, level)
    for file in target_path.iterdir():
        if file.is_dir():
            check_out_path(file, level+1)
        else:
            print_indented(file.name, level+1)


my_path = Path(r'C:\example folder')
check_out_path(my_path)

เอาท์พุท:

example folder
    folder
        textfile3.txt
    textfile1.txt
    textfile2.txt

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.