脚本:
#!/usr/bin/env python # encoding utf-8 import os import types Driver = "d:" # 输出D盘下的所有文件 for i in os.walk(Driver + os.sep + "python-study"): print (type(i)) print (i)
输出结果
<class 'tuple'>
('d:\\python-study', [], ['1.txt', 'a.py', 'a1.py', 'a2.py', 'a3-for.py', 'a4.-createFile.py', 'a5-r
eadFile.py', 'a6.py', 'a7.py', 'att2.py', 'attac.py', 'configfile.py', 'dict.py', 'lock.txt', 'mail.
properties', 'mail.py', 'mailConfig.ini', 'scocket.py', 'sendmail.zip', 'sendmail_linux.py', 'sendma
il_win.py'])
os.path.join()方法取出每个文件绝对路径
#!/usr/bin/env python # encoding utf-8 import os Driver = "d:" for root,dir,file in os.walk(Driver+ os.sep + "python-study"): for i in file: full_path = os.path.join(root,i) print (full_path)
D:\python-study>dict.py
d:\python-study\1.txt
d:\python-study\a.py
d:\python-study\a1.py
d:\python-study\a2.py
d:\python-study\a3-for.py
...
os.path.getsize()方法获取文件大小
#!/usr/bin/env python # encoding utf-8 import os Driver = "d:" for root,dir,file in os.walk(Driver+ os.sep + "python-study"): for i in file: full_path = os.path.join(root,i) filesize = os.path.getsize(full_path) print (full_path, filesize)
D:\python-study>dict.py
d:\python-study\1.txt 6
d:\python-study\a.py 227
d:\python-study\a1.py 389
d:\python-study\a2.py 310
d:\python-study\a3-for.py 150
d:\python-study\a4.-createFile.py 227
d:\python-study\a5-readFile.py 938
d:\python-study\a6.py 300
d:\python-study\a7.py 314
d:\python-study\att2.py 3606
d:\python-study\attac.py 2040
d:\python-study\configfile.py 272