介绍
讲解
-
概述
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
-
语法
walk()方法语法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
-
参数
top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
root -- 所指的是当前正在遍历的这个文件夹的本身的地址
dirs -- 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
files -- 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
topdown -- 可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。
-
返回值
该方法没有返回值。
实例
import os
import re
def get_mysql_log_home():
try:
mysql_bin_path = os.popen('which mysql').read()
mysql_bin_path = mysql_bin_path[:-2]
mysql_home = os.path.dirname(mysql_bin_path)
mysql_log_path = os.path.join(mysql_home, '..', 'data')
except IOError:
return ''
else:
print('## mysql_log_path: ',mysql_log_path)
return mysql_log_path
def get_log_file_list(path, preffix = 'mysql-bin'):
logFiles = []
try:
for root, dirs, files in os.walk(path):
print('## root, dirs, files: ',root, dirs, files)
for logFile in files:
pattern = '%s%s%s' % ('^(', preffix, ').*')
if (re.match(pattern, logFile)):
f = os.path.join(root, logFile)
print('## logFiles: ',f)
logFiles.append(f)
except Exception:
return []
else:
return logFiles
def Main():
logPath = get_mysql_log_home()
if logPath == '':
return 0
allLogFile = get_log_file_list(logPath)
if len(allLogFile) == 0:
return 0
try:
for f in allLogFile:
# os.remove(f)
print('## REMOVEF: ',f)
except Exception:
return 0
else:
return 1
if __name__ == '__main__':
print(Main())
@结果
('## mysql_log_path: ', '/home/mysql/bin/../data')
('## root, dirs, files: ', '/home/mysql/bin/../data', ['uep4x', 'oozie', 'hueomm', 'odpp', 'mysql', 'yita', 'dap_model', 'uep4x_caf_fm', 'uep4x_pm', 'azkaban', 'performance_schema', 'ranger', 'impalaomm', 'testhue', 'hiveomm', 'uep4x_log', 'sparkomm', 'test'], ['jfsh4.err', 'mysql-bin.index', 'mysql-bin.000016', 'ib_logfile1', 'ibdata1', 'mysql-bin.000015', 'jfsh4.pid', 'ib_logfile0'])
('## logFiles: ', '/home/mysql/bin/../data/mysql-bin.index')
('## logFiles: ', '/home/mysql/bin/../data/mysql-bin.000016')
('## logFiles: ', '/home/mysql/bin/../data/mysql-bin.000015')
......
('## REMOVEF: ', '/home/mysql/bin/../data/mysql-bin.index')
('## REMOVEF: ', '/home/mysql/bin/../data/mysql-bin.000016')
('## REMOVEF: ', '/home/mysql/bin/../data/mysql-bin.000015')