Iterate through folders, then subfolders and print filenames with path to text file

前端 未结 2 1212
野的像风
野的像风 2020-12-01 01:54

I am trying to use python to create the files needed to run some other software in batch. For part of this I need to produce a text file that loads the needed data files int

相关标签:
2条回答
  • 2020-12-01 02:02

    Charles' answer is good, but can be improved upon to increase speed and efficiency. Each item produced by os.walk() (See docs) is a tuple of three items. Those items are:

    1. The working directory
    2. A list of strings naming any sub-directories present in the working directory
    3. A list of files present in the working directory

    Knowing this, much of Charles' code can be condensed with the modification of a forloop:

    import os
    
    def list_files(dir):
        r = []
        for root, dirs, files in os.walk(dir):
            for name in files:
                r.append(os.path.join(root, name))
        return r
    
    0 讨论(0)
  • 2020-12-01 02:16

    Use os.walk(). The following will output a list of all files within the subdirectories of "dir". The results can be manipulated to suit you needs:

    import os                                                                                                             
                                                                                                                          
    def list_files(dir):                                                                                                  
        r = []                                                                                                            
        subdirs = [x[0] for x in os.walk(dir)]                                                                            
        for subdir in subdirs:                                                                                            
            files = os.walk(subdir).next()[2]                                                                             
            if (len(files) > 0):                                                                                          
                for file in files:                                                                                        
                    r.append(os.path.join(subdir, file))                                                                         
        return r                                                                                                          
    

    For python 3, change next() to __next__().

    0 讨论(0)
提交回复
热议问题