如何将一个目录下的所有文件,组装成一篇文章,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')