一 sys
用于python解释器相关的操作
#!/usr/bin/env python # coding=utf-8 import time import sys def view_bar(num, total): rate = num / total rate_num = int(rate * 100) r = ' %d%%' % (rate_num, ) sys.stdout.write(r) sys.stdout.flush() def view_bar2(num, total): rate = num / total rate_num = int(rate * 100) r = ' %s>%d%%' % ("="*num, rate_num, ) sys.stdout.write(r) sys.stdout.flush() for i in range(1, 101): time.sleep(0.1) view_bar2(i, 100)
二 os
用于操作系统级别相关的操作
遍历搜索目录 #!/usr/bin/env python # coding=utf-8 import os import fnmatch def all_files(root, patterns, single_level=False, yield_folders=False): """ 遍历文件夹目录和文件 :param root: 要遍历的文件夹 :param patterns: 搜索模式以";"号隔开 :param single_level: True,遍历一级目录, False, 全部遍历 :param yield_folders: True, 匹配目录, False, 不匹配目录 :yield os.path.join(path, name) 返回路径和文件名 """ patterns = patterns.split(';') for path, subdirs, files in os.walk(root): # 是否匹配目录 if yield_folders: files.extend(subdirs) files.sort() for name in files: for pattern in patterns: if fnmatch.fnmatch(name, pattern): yield os.path.join(path, name) break # 只遍历一级目录 if single_level: break # for path in all_files('/root/module2/day6', '*.py;*.txt', yield_folders=False, single_level=False): # print(path) ret = all_files('/root/module2/day6', '*.py;*.txt', yield_folders=False, single_level=False) for line in ret: print(line)