1. python遍历文件,使用os.walk()方法,这个方法能都遍历到所有文件。
# traversal files and print the size of these files
# how to use os.walk()
import os,sys
num = 0
targetdir = sys.argv[1]
for root, dirs, files in os.walk(targetdir):
print root
print files
num += len(files)
for name in files:
# print os.path.join(root, name)
print os.path.getsize(os.path.join(root, name))
print num
调用os.walk()方法,会返回一个三元组,root是当前路径,dirs是当前路径下的目录,files是当前路径下的文件。
os.walk()方法是对于目录树自上向下或者自下向上遍历,对于每个目录都会由一个三元组构成。对于该目录下的文件,没有目录信息( the names in the lists contain no path components.)所以需要调用os.path.join(root, files)形成完整的目录信息。
os.walk()不会改变当前的执行目录