自定义文件复制工具

2020-05-07  本文已影响0人  痞子_4ae7
# coding='utf-8'
"""
    task:自定义文件复制工具
        - 思路讲解
            - 打开源文件,判断源文件是否有效,有效进行后续操作
            - 新文件名字的生成   旧文件名+[复件]+.后缀(用到查找rfind,以及切片操作)
            - 开始复制文件(1. 整体复制    2.循环逐行复制)
            - 关闭文件
    version:1.0
    author:ZXQ
    date:2020-5-7
"""
import os


# 分割文件名和文件后缀的操作
# example:C:/Users/Administrator/PycharmProjects/Py20/test01.txt
def get_new_file_name(old_file):
    # 获取‘.’的索引
    index_of_spot = old_file.rindex('.')

    # 获取最后一个‘/’的索引
    index_of_backslash = old_file.rindex('/')

    # 获取原始文件路径
    old_file_path = old_file[:index_of_backslash + 1]
    # print('原始文件路径' + old_file_path)

    # 获取原始文件名
    # old_file_name = old_file[index_of_backslash + 1:]
    # print(old_file_name)

    # 获取文件后缀
    suffix = old_file[index_of_spot:]
    # print(suffix)

    # 新文件名
    new_file_name = old_file[index_of_backslash + 1:index_of_spot] + '[复制]' + suffix
    # print(new_file_name)

    # 返回新文件名
    return new_file_name, old_file_path, suffix


def copy_2_file(old_file):
    # 判断文件是否存在
    if os.path.exists(old_file):
        if get_new_file_name(old_file)[2] == '.txt':
            # 打开文件
            with open(old_file, 'r', encoding='utf-8') as f:
                # 读取文件中的内容
                content = f.read()

                # 得到新文件名
                new_file_name = get_new_file_name(old_file)[0]

                # 创建新文件
                new_file_path_name = get_new_file_name(old_file)[1] + new_file_name
                with open(new_file_path_name, 'w', encoding='utf-8') as new_file:
                    # 向新文件中写入内容
                    new_file.write(content)
                    print('文件复制成功!新文件命名为:%s' % new_file_name)
        else:
            print('暂不支持该格式的文件复制,敬请期待新版本!')
    else:
        print('目标文件:%s 不存在,请核实!' % old_file)


if __name__ == '__main__':
    copy_2_file('C:/Users/Administrator/PycharmProjects/Py20/test01.txt')
    copy_2_file('D:/Users/Administrator/PycharmProjects/Py20/test01.txt')
    copy_2_file('C:/Users/Administrator/Desktop/哈哈哈.txt')
    copy_2_file('C:/Users/Administrator/Desktop/pub60.pdf')

上一篇 下一篇

猜你喜欢

热点阅读