file_utils.py 2.92 KB
Newer Older
yangpengflag committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
import os
import shutil
import logging




# 实现图片文件的复制
'''
定义一个函数,接受两个参数,第一个参数是原始图片文件,第二个参数是复制到的路径
'''
def copy_image(source_file,target_path):

    if not os.path.exists(target_path):
        os.makedirs(target_path)

    if os.path.exists(source_file):
        # shutil.copy(r'要复制的文件路径(路径+文件)',r'复制到的路径') bits模式
        shutil.copy(source_file, target_path)
        # shutil.copyfileobj(open(source_file, 'rb'), open(target_path, 'wb'))
        print(source_file)
        print(target_path)


"""
    这里要考虑,给定的参数file_path是文件还是文件夹,如果是文件则直接列出来文件名称就可以
    如果是文件夹,那么要列出这个文件夹下所有的文件名称,同时要考虑,文件夹下是否还有文件夹
    直到保证此文件夹下再不包含文件夹,列出所有的文件名称即可
    # 每当读取一个文件夹时,打一个info级别的log,标记开始读取哪个文件夹
"""
def get_files(file_path):
    if not os.path.exists(file_path):
        logging.warning("地址不存在,请检查")
    if os.path.isfile(file_path):
        print(file_path[0:file_path.find("\\|/")])
        return file_path

    if os.path.isdir(file_path):
        print("该地址是文件夹")
        files = os.listdir(file_path)
        for i in range(len(files)):
            logging.info("开始读取文件夹%s" %files[i])
            print("开始读取文件夹%s" %files[i])
            filelist = os.path.join(file_path,files[i])
            if len(filelist) > 0:
                get_files(os.path.abspath(filelist))

    print("文件读取完毕")



'''
从一个目录将全部文件(包含子目录)copy到另外一个目录,只copy文件,不操作文件夹
'''
def copy_dir_2_dir(source_path,target_path):

    if not os.path.exists(target_path):
        os.makedirs(target_path)

    if os.path.exists(source_path):
        # root 所指的是当前正在遍历的这个文件夹的本身的地址
        # dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)
        # files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录,只copy子目录中的文件,目录结构不copy)
        for root, dirs, files in os.walk(source_path):
            print("root:%s" % root)
            print("dirs:%s" % dirs)
            print("files:%s" % files)
            for file in files:
                src_file = os.path.join(root, file)
                shutil.copy(src_file, target_path)
                print(src_file)

    print('copy files finished!')




# copy图片
# copy_image("D:/wechaticon.png","D:/test1/")
#
#  # copy视频
# copy_image("D:/珠宝展示网站用视频新版_x264.mp4","D:/test1/")


# get_files("D:\\wechaticon.png")
# get_files("D:\\test1")

copy_dir_2_dir("D:\\壁纸","D:\\test1")