file_filter.py
"""
根据文件类型 和 文件大小,将文件进行分类。复制。
"""
import os
import shutil
import filetype
# ------------------------------------------------------------------
# 待分类的文件目录,里面都是文件,没有二级目录。
base_path = ""
# 分类后,目标文件目录
to_path = ""
# 文件大小界限,单位B,例如4M(近似)
size_limit = 400000
# ------------------------------------------------------------------
def guess_filetype(file_path):
"""
检测文件类型
"""
try:
file_type = filetype.guess(file_path).extension
except AttributeError:
file_type = None
return file_type
def copy_file(org_path,dst_path):
"""
复制文件
:param org_path:文件原地址,必须是文件地址
:param dst_path:文件目标地址,可以是目录/文件
:return:None
"""
shutil.copy(org_path,dst_path)
def get_file_size(file_path):
"""获取文件大小"""
file_size = os.path.getsize(file_path)
return file_size
def create_folder(dst_path):
"""
判断目标路径是否存在
如果不存在,则创建
存在则忽略
:return:None
"""
if not os.path.exists(dst_path):
print("create folder....",dst_path)
os.makedirs(dst_path)
def get_copy_info(file_name):
"""
获取文件路径和目标地址
cp file dst_path
:return:
"""
org_path = os.path.join(base_path,file_name)
size_name = "big" if get_file_size(org_path) >= size_limit else "small"
file_type = guess_filetype(org_path)
dst_path = os.path.join(to_path,str(file_type),size_name)
create_folder(dst_path)
return org_path,dst_path
def main():
"""主函数"""
file_list = os.listdir(base_path)
for file_name in file_list:
org_path ,dst_path = get_copy_info(file_name)
copy_file(org_path, dst_path)
if __name__ == '__main__':
main()