python 组装目录下所有文件

如何将一个目录下的所有文件,组装成一篇文章,python 代码:

# -*-coding:utf-8-*-
import os

path = 'D:\\data'
output_path = 'result.txt'

with open(output_path, 'w', encoding='utf8') as outf:
    for filename in os.listdir(path):
        if not filename.endswith("(1).txt") and filename.endswith(".txt"):
            outf.write(filename)
            outf.write('\n')

    print('finished write file index')

    for i in range(10):
        outf.write('\n')

    for filename in os.listdir(path):
        try:
            if not filename.endswith("(1).txt") and filename.endswith(".txt"):
                file_path = os.path.join(path, filename)
                with open(file_path, 'r', encoding='utf-8') as inf:
                    for line in inf:
                        outf.write(line)
        except:
            try:
                if not filename.endswith("(1).txt") and filename.endswith(".txt"):
                    file_path = os.path.join(path, filename)
                    with open(file_path, 'r', encoding='gbk') as inf:
                        for line in inf:
                            outf.write(line)
            except:
                print('failed parse file=>', filename)

        outf.write('\n\n')
        outf.write('-' * 10)
        outf.write(filename)
        outf.write('-' * 10)
        outf.write('\n\n')

    print('finished write all')



个人资料
时海
等级:8
文章:272篇
访问:16.0w
排名: 2
上一篇: tensorflow2.0创建Tensor基础操作
下一篇:python 组装目录下所有文件
标签: python、面试题
隐藏