python 合并目标文件夹中多个txt文件到指定文件中

# coding = 'utf-8'
# description: 合并目标文件夹中多个txt文件,到指定文件中。
import os


def file_merge_to_one(dirpath):
    # 创建一个新的文档
    newfn = dirpath.split('\\')[-1] + '.txt'
    f = open(newfn, 'w', encoding='utf-8')
    for filename in os.listdir(dirpath):
        if os.path.isfile(os.path.join(dirpath, filename)) and filename.split(r'.')[-1] == 'txt':
            if newfn != filename:
                print('准备整合文件:', filename)
                f.write('\n#{}\n'.format(filename.split(r'.')[0]))
                filepath = os.path.join(dirpath, filename)
                for line in open(filepath, 'r', encoding='utf-8', errors='ignore'):
                    f.write(line)
        elif os.path.isdir(os.path.join(dirpath, filename)):
            file_merge_to_one(os.path.join(dirpath, filename))
        else:
            print("跳过文档: ", filename)
    f.close()


def del_empty_file(dirpath):
    # 删除空目录或因多级目录产生的空文档
    for file in os.listdir(dirpath):
        filepath = os.path.join(dirpath, file)
        if os.path.isfile(filepath) and os.path.getsize(filepath) == 0:
            os.remove(filepath)


if __name__ == '__main__':
    user_input = input("请输入需要合并的文件夹路径(默认为当前工作目录): ") or os.getcwd()
    dirpath = os.path.join(os.getcwd(), user_input)
    print(dirpath)
    file_merge_to_one(dirpath=dirpath)
    del_empty_file(dirpath=dirpath)
posted @ 2022-12-08 11:15  f_carey  阅读(305)  评论(0编辑  收藏  举报