zoukankan      html  css  js  c++  java
  • 将多个文件夹内的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()
  • 相关阅读:
    原创:Qt自定义拖放
    看下最近公司的招聘需求
    leveldb阅读心得
    Relationship between the FIX Protocol's OrdID, ClOrdID, OrigClOrdID?
    Wait Functions
    全局变量与单例模式
    Asynchronous I/O
    QuickFix MsgHandler
    第一个Java程序
    (原創) Function Pointer、Delegate和Function Object (C/C++) (template) (.NET) (C#)
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/6797429.html
Copyright © 2011-2022 走看看