Python小代码_15_遍历指定路径下的所有文件和文件夹,并格式化输出文件路径文件名和文件夹名,文件大小,修改时间

时间:2022-05-08 16:35:19

遍历指定路径下的所有文件和文件夹,并格式化输出文件路径文件名和文件夹名,文件大小,修改时间

import os
import datetime def print_tree(dir_path):
for name in sorted(os.listdir(dir_path)):
full_path = os.path.join(dir_path, name)
file_size = os.path.getsize(full_path)
modify_time = datetime.datetime.fromtimestamp(os.path.getmtime(full_path))
print('%s\t%s\t%s' % (full_path.ljust(26), str(file_size).ljust(6), modify_time))
if os.path.isdir(full_path):
print_tree(full_path) if __name__ == '__main__':
print_tree('e:/test') '''
e:/test\111 4096 2018-05-02 17:42:51.417505
e:/test\111\aaa 0 2018-05-02 17:43:05.443528
e:/test\111\aaa\efg.docx 0 2018-05-02 17:42:57.966647
e:/test\111\abc.xlsx 6610 2018-05-02 17:42:38.974835
e:/test\222 0 2018-05-02 17:21:28.839784
e:/test\333 0 2018-05-02 17:21:32.269475
e:/test\444.txt 0 2018-05-02 17:22:55.221821
e:/test\Hello.txt 0 2018-05-02 17:27:56.921054
e:/test\a123.txt 490 2018-05-06 18:42:55.688596
e:/test\marshal_test.dat 102 2018-05-06 20:32:17.170066
e:/test\sample_pickle.dat 235 2018-05-06 19:37:36.338858
e:/test\sample_struct.dat 18 2018-05-06 20:12:12.599015
e:/test\shelve_test.dat.bak 125 2018-05-06 20:15:30.979789
e:/test\shelve_test.dat.dat 3083 2018-05-06 20:15:30.979789
e:/test\shelve_test.dat.dir 125 2018-05-06 20:15:30.979789
'''