Browse folders in python


I have the following code:

import os, glob
from obspy.core import read

for fname in glob.glob('BC.*'):
    print "<==== ", fname
    #  Quita la extension (.msd), si existe
    if(len(arch) > 7):
       del arch[-1]
    newName = '.'.join(arch)
    st = read(fname)
    segmentos = len(st)
    # cuenta el numero de segmentos del archivo para hacer el cambio en cada uno de ellos
    for i in range(0, segmentos):
    print "====> ", newName , " Ok"
    st.write(newName, format="MSEED")
    print " --- ", fname, " [x]" 

It works well, just to run the script I have to be inside the folder that will make the change, and it is tedious to be running the script inside each folder.

How could I make you go through all the folders without having to put it inside it?

I have the folders like this:

asked by Armando 16.02.2016 в 18:55

2 answers


I wrote this code to list all the files in a folder and its subfolders:

import os
import sys
from os import listdir
from os.path import isfile, isdir, join

def listdir_recurd(files_list, root, folder, checked_folders):

    if (folder != root):

    for f in listdir(folder):
        d = join(folder, f)       

        if isdir(d) and d not in checked_folders:
            listdir_recurd(files_list, root, d, checked_folders)
            if isfile(d):  # si no hago esto, inserta en la lista el nombre de las carpetas ignoradas
                files_list.append(join(folder, f))

    return files_list

The function is used like this:

filez = listdir_recurd([], 'D:\test0', 'D:\test0', []) # esto lista todos los archivos
filez = listdir_recurd([], 'D:\test', 'D:\test', ['D:\test\t1', 'D:\test\t2']) # esto omite las carpetas 'D:\test\t1' y 'D:\test\t2'
filez = listdir_recurd([], 'D:\test', 'D:\test', ['D:\test\t1']) # esto omite la carpeta 'D:\test\t1'

The filez list contains the names and absolute paths of all the found files, so you can apply your algorithm to them. In your case it would be used as:

filez = listdir_recurd([], 'C:\Datos', 'C:\Datos', [])

More info, here: link

answered by 17.02.2016 в 16:15

I know two ways to go through directories where each folder inside is displayed.

Form 1

import os
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Directorio encontrado: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

Form 2

import os

rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir, topdown=False):
    print('Directorio encontrado: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

Both browse the directories and subdirectories contained. You can adapt your code using these forms.

answered by 16.02.2016 в 19:26