Hướng dẫn os walk python - trăn đi bộ hệ điều hành

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  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

27 hữu ích 4 bình luận chia sẻ 4 bình luận chia sẻ

Miêu tả

Phương thức walk[] tạo các tên file trong cây thư mục bằng việc quét qua cây đó từ trên xuống hoặc từ dưới lên.walk[] tạo các tên file trong cây thư mục bằng việc quét qua cây đó từ trên xuống hoặc từ dưới lên.

Cú pháp

Cú pháp của walk[] trong Python:walk[] trong Python:

os.walk[top[, topdown=True[, onerror=None[, followlinks=False]]]]

Chi tiết về tham số:

  • top -- Thư mục cấp cao nhất trong thư mục root, gồm ba trường [path_thu_muc, ten_thu_muc, ten_file] -- Thư mục cấp cao nhất trong thư mục root, gồm ba trường [path_thu_muc, ten_thu_muc, ten_file]

  • topdown -- Nếu tham số tùy ý này là True hoặc không được xác định, các thư mục được quét từ trên xuống. Nếu là False, các thư mục được quét từ dưới lên. -- Nếu tham số tùy ý này là True hoặc không được xác định, các thư mục được quét từ trên xuống. Nếu là False, các thư mục được quét từ dưới lên.

  • onerror -- Hiển thị một lỗi để tiếp tục tiến trình quét, hoặc tạo một ngoại lệ để ngừng tiến trình. -- Hiển thị một lỗi để tiếp tục tiến trình quét, hoặc tạo một ngoại lệ để ngừng tiến trình.

  • followlinks -- Nếu được thiết lập là true, các visit dir được trỏ bởi các link tượng trưng. -- Nếu được thiết lập là true, các visit dir được trỏ bởi các link tượng trưng.

Trả về giá trị

Phương thức này không trả về bất cứ giá trị nào.

Quảng cáo

Chương trình Python ví dụ

Ví dụ sau minh họa cách sử dụng của walk[] trong Python.

 

import os
for root, dirs, files in os.walk[".", topdown=False]:
    for name in files:
        print[os.path.join[root, name]]
    for name in dirs:
        print[os.path.join[root, name]]

Chạy chương trình Python trên sẽ quét cây thư mục từ dưới lên.

./tmp/test.py
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp

Nếu bạn thay đổi giá trị của topdown thành True, thì kết quả là:topdown thành True, thì kết quả là:

./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py

file_io_trong_python.jsp

Bài viết liên quan

  • 160 bài học ngữ pháp tiếng Anh hay nhất

  • 155 bài học Java tiếng Việt hay nhất

  • 100 bài học Android tiếng Việt hay nhất

  • 247 bài học CSS tiếng Việt hay nhất

  • 197 thẻ HTML cơ bản

  • 297 bài học PHP

  • 101 bài học C++ hay nhất

  • 97 bài tập C++ có giải hay nhất

  • 208 bài học Javascript có giải hay nhất

Bài Viết Liên Quan

Chủ Đề