Hướng dẫn python os walk recursive - python os walk đệ quy

thử cái này:

#!/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))

Bạn sẽ nhận được điều này:

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

Chìa khóa ở đây là sử dụng os.path.join () khi chúng tôi đọc các tệp. Lưu ý rằng các tên trong danh sách không có thành phần đường dẫn. Để có được một đường dẫn đầy đủ (bắt đầu bằng đầu) đến một tệp hoặc thư mục trong dirpath, do os.path.join (dirpath, fileName).

Hướng dẫn python os walk recursive - python os walk đệ quy

Hướng dẫn python os walk recursive - python os walk đệ quy






Đầu ra từ mã:


home = os.path.expanduser("~")
2 Thư mục đệ quy đi qua 2

Đây là một ví dụ khác. Nó đọc trong cmakelists.txt và tạo tệp CSV với các mục tiêu.

home = os.path.expanduser("~")

Tệp CSV trông như thế này:

home = os.path.expanduser("~")
5 Thư mục đệ quy đi qua 3


os.path.basename() vs. os.path.dirname()

Điều này gần giống như những cái trước.os.path.basename() and os.path.dirname() functions?

Tôi cần tìm các tệp có nhiều hơn một đơn vị quảng cáo của Google (tôi chỉ có một trong các loại trên mỗi trang).os.path.split(path) function to split the pathname path into a pair; (head, tail).

  1. path="/foo/bar/item""/foo/bar/item"
  2. Vì vậy, trong quá trình chuyển tệp đệ quy, tôi chỉ bao gồm các tệp ( *.php) không *.png, *.txt, v.v. Ngoài ra, tôi phải đếm sự xuất hiện của đơn vị quảng cáo trong một tệp. Nếu một tệp có nhiều hơn một đơn vị, mã này sẽ in ra hai điều: đường dẫn đầy đủ và số đếm.os.path.dirname(path) function returns the head of the path.
    >>> os.path.dirname(path)
    '/foo/bar'
    
  3. Mẫu đầu ra:os.path.basename(path) function returns the tail of the path.
    >>> os.path.basename(path)
    'item'
    

home = os.path.expanduser("~")
7 Thư mục đệ quy đi qua 4

  1. path="/foo/bar/item/""/foo/bar/item/"
  2. Gần đây, tôi đã chuyển sang HTTPS (SSL) từ HTTP. Nhưng phát hiện ra, CSS của tôi không tải đúng cách và nó đã phá vỡ các trang của tôi. Hóa ra, tôi đã sử dụng http, ví dụ: "http://apis.google.com/js/plusone.js". Vì vậy, tôi đã phải duyệt tất cả các tệp và thay thế nó thành "//apis.google.com/js/plusone.js".os.path.dirname(path) function returns the head of the path.
    >>> os.path.dirname(path)
    '/foo/bar/item'
    
  3. Đây là tập lệnh tôi đã sử dụng cho nhiệm vụ:os.path.basename(path) function returns the tail of the path.
    >>> os.path.basename(path)
    ''
    





os.walk()

os.walk(top, topdown=True, onerror=None, followlinks=False)

Tôi đã thay thế khá nhiều cuộc gọi API bằng một cái gì đó như thế này: "//apis.google". Chỉ cần bỏ "http:". Tôi cũng loại trừ một số tệp như phương tiện hoặc các tệp được nén. Tôi đã không sử dụng thay thế tại chỗ vì phiên bản Python của tôi là 2.7os.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up.

Đầu ra (chỉ liệt kê các tệp đã xử lý):top, it yields a 3-tuple:
(dirpath, dirnames, filenames)

Truyền tải các thư mục đệ quydirpath is a string for the path to the directory. The dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). The filenames is a list of the names of the non-directory files in dirpath.

Tìm kiếm trang web Bogotobogo.com:dirpath, do os.path.join(dirpath, name).

Như một bản xem trước, chúng tôi nhận được đầu ra sau từ cây như thế này:

Hướng dẫn python os walk recursive - python os walk đệ quy

import os
path = "./TEST"

for root,d_names,f_names in os.walk(path):
	print root, d_names, f_names

Output:

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
0

Chúng tôi có thể tạo một đường dẫn đầy đủ cho mỗi tệp:

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
1

Đầu ra:

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
2 Như một ví dụ khác, chúng ta sẽ sử dụng cây bên dưới:

As another example, we're going to use the tree below:

Hướng dẫn python os walk recursive - python os walk đệ quy

dirpath::

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
3

Output:

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
4 Dirs:

dirs:

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
5

Output:

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
6 Tệp:

files:

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
7

Output:

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
8

Liệt kê các tập tin trong thư mục đệ quy?

Đây là mã:

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
9

Giả sử bây giờ chúng ta đang ở trong thư mục cây, thì đầu ra sẽ trông như thế này:TREE directory, then the output should look like this:

home = os.path.expanduser("~")
0

Hướng dẫn python os walk recursive - python os walk đệ quy

Thư mục đệ quy đi qua

Làm thế nào để đi qua một cây thư mục?

Một trong những câu trả lời có thể là sử dụng os.walk () để đi ngang qua các thư mục.os.walk() to recursively traverse directories.

Vì vậy, trong phần này, chúng tôi muốn in tất cả các nội dung tệp một cách đệ quy bằng cách sử dụng os.walk ():os.walk():

home = os.path.expanduser("~")
1

Chìa khóa ở đây là sử dụng os.path.join () khi chúng tôi đọc các tệp. Lưu ý rằng các tên trong danh sách không có thành phần đường dẫn. Để có được một đường dẫn đầy đủ (bắt đầu bằng đầu) đến một tệp hoặc thư mục trong dirpath, do os.path.join (dirpath, fileName).os.path.join() when we read the files. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, filename).

Đầu ra từ mã:

home = os.path.expanduser("~")
2 Thư mục đệ quy đi qua 2


Recursive directory traversing 2

Đây là một ví dụ khác. Nó đọc trong cmakelists.txt và tạo tệp CSV với các mục tiêu.CMakeLists.txt, and generate a csv file with the targets.

home = os.path.expanduser("~")
3

Output:

home = os.path.expanduser("~")
4

Tệp CSV trông như thế này:

home = os.path.expanduser("~")
5 Thư mục đệ quy đi qua 3


Recursive directory traversing 3

Điều này gần giống như những cái trước.

Tôi cần tìm các tệp có nhiều hơn một đơn vị quảng cáo của Google (tôi chỉ có một trong các loại trên mỗi trang).

Vì vậy, trong quá trình chuyển tệp đệ quy, tôi chỉ bao gồm các tệp ( *.php) không *.png, *.txt, v.v. Ngoài ra, tôi phải đếm sự xuất hiện của đơn vị quảng cáo trong một tệp. Nếu một tệp có nhiều hơn một đơn vị, mã này sẽ in ra hai điều: đường dẫn đầy đủ và số đếm.

Đây là mã:

home = os.path.expanduser("~")
6

Mẫu đầu ra:

home = os.path.expanduser("~")
7 Thư mục đệ quy đi qua 4


Recursive directory traversing 4

Gần đây, tôi đã chuyển sang HTTPS (SSL) từ HTTP. Nhưng phát hiện ra, CSS của tôi không tải đúng cách và nó đã phá vỡ các trang của tôi. Hóa ra, tôi đã sử dụng http, ví dụ: "http://apis.google.com/js/plusone.js". Vì vậy, tôi đã phải duyệt tất cả các tệp và thay thế nó thành "//apis.google.com/js/plusone.js".http://apis.google.com/js/plusone.js". So, I had to browse all files, and replace it to "//apis.google.com/js/plusone.js".

Đây là tập lệnh tôi đã sử dụng cho nhiệm vụ:

home = os.path.expanduser("~")
8

Tôi đã thay thế khá nhiều cuộc gọi API bằng một cái gì đó như thế này: "//apis.google". Chỉ cần bỏ "http:". Tôi cũng loại trừ một số tệp như phương tiện hoặc các tệp được nén. Tôi đã không sử dụng thay thế tại chỗ vì phiên bản Python của tôi là 2.7

Đầu ra (chỉ liệt kê các tệp đã xử lý):

home = os.path.expanduser("~")
9