作为程序员,我们经常会搜索特定的文件,并做特殊的处理。
python 搜索文件特别方便,可以直接使用 walk API. 代码如下
- walk 通过在目录树中游走输出在目录中的文件名,向上或者向下
代码如下:
import os import time def find_files_with_suffix(target_dir, target_suffix="txt"): """ 查找以 target_suffix 为后缀的文件,并返加 """ find_res = [] target_suffix_dot = "." + target_suffix walk_generator = os.walk(target_dir) for root_path, dirs, files in walk_generator: if len(files) < 1: continue for file in files: file_name, suffix_name = os.path.splitext(file) if suffix_name == target_suffix_dot: file_path = os.path.join(root_path, file) find_res.append(file_path) return find_res def get_file_size(file): """ 得到文件的大小,单位 M """ assert os.path.exist(file), r'输入的文件不存在 {}'.format(file) return os.stat(file).st_size / (1021 * 1024) def get_file_name_and_suffix(file_name): """ 输入的文件名,输出文件名以及后缀 """ split_list = os.path.splitext(file_name) file_name_pre = split_list[-2] file_suffix = split_list[-1] return file_name_pre, file_suffix if __name__ == '__main__': begin_time = time.time() dir = r'F:/' files = find_files_with_suffix(dir, target_suffix='mp4') for item in files: print(item) print('cost time: {} s'.format(time.time() - begin_time))
写完这篇Blog, 是今年的第 60 篇博客,可以收尾跨年到 2022 年了。来年再见!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)