練手,用Python實現Linux下的tree命令

2021-06-12 20:49:11 字數 1605 閱讀 6257

用python實現了linux下的tree命令的基本功能,沒有實現各種引數。寫得不好,歡迎拍磚。

覺得原來的沒有python的風格,換了乙個寫法,感覺格式不好看。。。

新的:

import os

def tree(path):

def tree_iter(path, prefix=''):

path = os.path.abspath(path)

listpath = os.listdir(path)

for p in listpath:

islast = listpath.index(p) == len(listpath)-1

abspath = os.path.join(path, p)

print_tree(p, prefix, islast)

if os.path.isdir(abspath):

next_prefix = prefix

next_prefix += ' ' if islast else '| '

tree_iter(abspath, next_prefix)

def print_tree(path, prefix, islast):

print(prefix, end='')

print('\\-- ' if islast else '|-- ', end='')

print(path)

print(path)

tree_iter(path)

if __name__ == '__main__':

path = input('path?\n')

tree(path)

舊的:

import os

def tree_iter(path, prefix=''):

path = os.path.abspath(path)

listpath = os.listdir(path)

for p in listpath:

islast = listpath.index(p) == len(listpath)-1

abspath = os.path.join(path, p)

print_tree(p, prefix, islast)

if os.path.isdir(abspath):

next_prefix = prefix

next_prefix += ' ' if islast else '| '

tree_iter(abspath, next_prefix)

def print_tree(path, prefix, islast):

print(prefix, end='')

print('\\-- ' if islast else '|-- ', end='')

print(path)

def tree(path):

print(path)

tree_iter(path)

if __name__ == '__main__':

path = input('path?\n')

tree(path)

python練手題目 Python練手題目(七)

1.計算重複字母出現的次數 編寫乙個函式,該函式將返回在輸入字串 現多次 不同的不區分大小寫的 字母字元和數字的計數。可以假定輸入字串僅包含字母 大寫和小寫 和數字。例如 abcde 0 no characters repeats more than once aabbcde 2 a and b a...

python練手實戰之實現貪吃蛇

python的基礎已經學的差不多了,接下來想通過練習一些小的專案將python的知識進行總結和整合 首先進行學習的就是貪吃蛇遊戲,那咱們就正式開始貪吃蛇遊戲的實現。首先引入一些本實驗需要用到的資源 import pygame import sys import random 對於pygame的安裝可...

Python練手專案0011

敏感詞文字檔案 filtered words.txt,裡面的內容為以下內容,當使用者輸入敏感詞語時,則列印出 freedom,否則列印出 human rights。coding utf 8 created on thu jan 12 13 55 35 2017 author sky def tran...