1. 程式人生 > >[Python](系統程式設計) 遍歷主機檔案系統

[Python](系統程式設計) 遍歷主機檔案系統

[Python](系統程式設計) 遍歷主機檔案系統

Terminal 互動,根據使用者輸入顯示該目錄下的所有檔案(夾)

Code

#!/usr/bin/env python3

"""folder.py
Author: Joseph Lin
E-mail: [email protected]
Social:
  https://github.com/RDpWTeHM/
  https://blog.csdn.net/qq_29757283


Usage:
  === windows cmd.exe # for example ===
  > python3 folder.py "D:\"
  ...        False
  Software   True
  ...

  entry one dir('q' to quit): Software
  ...   False
  ...   True
  ...   False
  ...

  entry one dir('q' to quit): ..\
  ### use "..\" could return last dir.

  entry one dir('q' to quit): q
  >

TODO
  N/A

"""
import os import sys if sys.platform == 'linux': ''' Reference: [Python] 邊邊角角筆記 > 判斷當前執行平臺: https://blog.csdn.net/qq_29757283/article/details/83689149#_9 ''' import readline else: pass try: begin_dir = sys.argv[1] except IndexError: print("usage: %s <dir>"
% sys.argv[0]) sys.exit(1) def print_files_is_dir_in(path): files = os.listdir(path) for file in files: text = "{} is dir?".format(file) is_dir = os.path.join(path, file) print("{:50} {}".format(text, os.path.isdir(is_dir))) def main(): global begin_dir last_dir =
begin_dir print_files_is_dir_in(last_dir) select_dir = input("\nentry one dir('q' to quit): ") while select_dir != 'q': last_dir = os.path.join(last_dir, select_dir) if os.path.isdir(last_dir): print_files_is_dir_in(last_dir) else: print("the enter not a dir, quit!") sys.exit(0) select_dir = input("\nentry one dir('q' to quit): ") if __name__ == "__main__": main()

Test

> python3 folder.py "D:\"
Software              True
TEMP                  True
Documents             True
...

entry one dir('q' to quit): Documents
ProgrammingPython     False
flentPython_examples  True
...

entry one dir('q' to quit): q
>
>