将多个文件夹内的txt合并

import os
import re

def text_create(name):
    """
    创建txt文件夹
    """
    desktop_path = '/home/xinghe/PycharmProjects/TestProject/naochuxie/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path,'w')

    file.close()
    print('Done')



def VisitDir(path):
    """
    按照顺序返回文件夹下所有的txt路径
    """
    li = os.listdir(path)

    num_text = []
    for i in li:
        num_text.append(re.findall('\d+',i))
    number = []

    for index,v in enumerate(num_text):
        number = v+number
    num = sorted(list(map(int,number)))


    path_list = []
    for i in num:
        i = str(i)+'.txt'
        path_list.append(i)
    print(path_list)


    path_num = []
    for p in path_list:
        pathname = os.path.join(path,p)
        if not os.path.isfile(pathname):
           VisitDir(pathname)
        else:
            path_num.append(pathname)
    return path_num




rootdir = '/home/xinghe/abc/naochuxie'  #打开多个文件夹最外层的文件夹
list_str = os.listdir(rootdir)
file_str = []
for i in range(0,len(list_str)):
    path = os.path.join(rootdir,list_str[i])
    file_str.append(path)
print(file_str)




for index,value in enumerate(file_str):
    if __name__ == '__main__':
        path = value
        print(VisitDir(path))

    text_create(str(index))  # 调用函数
    # allfile = open('/home/xinghe/all.txt','a+')
    file_path = str(os.getcwd()) #得到当前工作目录,即当前Python脚本工作的目录路径 a+为在文本后追加
    print(file_path)

    allfile = open(file_path+'/datas/%s.txt'% index, 'a+')  #打开创建的txt文件

    for name in VisitDir(path):
        fi = open(name,encoding='gbk')
        while True:
            s = fi.read(16*1024)
            if not s:
                break
            allfile.write(s)
        fi.close()
    allfile.close()

 

posted on 2017-05-02 18:00  星河赵  阅读(812)  评论(0编辑  收藏  举报

导航