Перебирать многие каталоги в Python [Python3]

Итак, я работал над программой, которая должна обрабатывать каждый файл в определенном каталоге и делать что-то в зависимости от файла. Этот бит готов (код ниже), однако мне действительно нужно расширить его, чтобы я мог анализировать столько каталогов, сколько необходимо, и чтобы программа последовательно просматривала их все. Мой код выглядит следующим образом (извинения за действительно неуклюжий, плохой код):

def createTemplate( self, doType = 0, bandNameL = None, bandName430 = None ):

    '''
    Loads the archive of each file in a directory.
    Depending on the choice made on initialization, a template will be
    created for one band (of the user's choosing) or all bands.
    Templates are saved in self.directory (either CWD or whatever the user
    wishes) as 1D numpy arrays, .npy. If arguments are not provided for the
    template names (without the .npy suffix), default names will be used.

    Useage of the doType parameter: 0 (default) does both bands and returns a tuple.
    1 does only the L-band.
    2 does only the 430-band.
    '''

    print( "Beginning template creation..." )

    # Initialize the file names if given
    nameL = str( bandNameL ) + ".npy"
    name430 = str( bandName430 ) + ".npy"

    # Set the templates to empty arrays
    self.templateProfile430, self.templateProfileL = [], []

    # Set the call counters for the creation scripts to 0
    self._templateCreationScript430.__func__.counter = 0
    self._templateCreationScriptL.__func__.counter = 0

    # Cycle through each file in the stored directory
    for file in os.listdir( self.directory ):
        # Set the file to be a global variable in the class for use elsewhere
        self.file = file

        # Check whether the file is a fits file
        if self.file.endswith( ".fits" ) or self.file.endswith( ".refold" ):

            # Check if the file is a calibration file (not included in the template)
            if self.file.find( 'cal' ) == -1:

                # Open the fits file header
                hdul = fits.open( self.directory + self.file )

                # Get the frequency band used in the observation.
                frequencyBand = hdul[0].header[ 'FRONTEND' ]

                # Close the header once it's been used or the program becomes very slow.
                hdul.close()

                # Check which band the fits file belongs to
                if frequencyBand == 'lbw' or frequencyBand == 'L_Band':

                    if doType == 0 or doType == 1:
                        self.templateProfileL = self._templateCreationScriptL()

                        # Check if a save name was provided
                        if bandNameL == None:
                            np.save( self.directory + "Lbandtemplate.npy", self.templateProfileL )
                        else:
                            np.save( self.directory + nameL, self.templateProfileL )
                    else:
                        print( "L-Band file" )

                elif frequencyBand == '430':

                    if doType == 0 or doType == 2:
                        self.templateProfile430 = self._templateCreationScript430()

                        # Check if a save name was provided
                        if bandName430 == None:
                            np.save( self.directory + "430bandtemplate.npy", self.templateProfile430 )
                        else:
                            np.save( self.directory + name430, self.templateProfile430 )
                    else:
                        print( "430-Band file" )

                else:
                    print( "Frontend is neither L-Band, nor 430-Band..." )

            else:
                print( "Skipping calibration file..." )


        else:
            print( "{} is not a fits file...".format( self.file ) )

    # Decide what to return based on doType
    if doType == 0:
        print( "Template profiles created..." )
        return self.templateProfileL, self.templateProfile430
    elif doType == 1:
        print( "L-Band template profile created..." )
        return self.templateProfileL
    else:
        print( "430-Band template profile created..." )
        return self.templateProfile430

Итак, в настоящее время он отлично работает для одного каталога, но просто нужно знать, как изменить для нескольких каталогов. Спасибо всем, кто может помочь.

РЕДАКТИРОВАТЬ: self.directory инициализируется при инициализации класса, поэтому, возможно, вместо этого нужно что-то изменить:

class Template:

'''
Class for the creation, handling and analysis of pulsar template profiles.
Templates can be created for each frequency band of data in a folder which
can either be the current working directory or a folder of the user's
choosing.
'''

def __init__( self, directory = None ):

    # Check if the directory was supplied by the user. If not, use current working directory.
    if directory == None:
        self.directory = str( os.getcwd() )
    else:
        self.directory = str( directory )

вы можете получить список файлов / каталогов по пути, используя os.listdir(path)

Tushar Aggarwal 13.07.2018 10:37

Я использовал os для некоторых вещей, таких как listdir, но я не очень хорошо его понимаю.

zhn11tau 13.07.2018 10:37

Посмотрите sys.argv, os.walk и т. д. Совершенно непонятно, что вы здесь пытаетесь сделать.

Mad Physicist 13.07.2018 10:38

Кроме того, если у вас возникли проблемы с пониманием основных функций, вам понадобится учебное пособие, а не вопрос SO.

Mad Physicist 13.07.2018 10:39

Мне абсолютно нужен учебник, но я не могу найти тот, который мне понятен. Я действительно плохо разбираюсь в программировании. Мне просто нужен фрагмент кода, который будет перебирать мой каталог, добираться до конца, затем начинать итерацию через второй каталог и так далее, пока я не дойду до конца всех указанных мной каталогов.

zhn11tau 13.07.2018 10:47
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
5
41
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вот как вы можете запускать свою логику в разных каталогах:

>>> import os
>>> path = './python'
>>> for name in os.listdir(path) :
...     newpath = path+'/'+name
...     if os.path.isdir(newpath) :
...             for filename in os.listdir(newpath) :
...                     # do the work
...                     filepath = newpath + '/' + filename
...                     print(filepath)
...

Спасибо. Это как раз то, что мне было нужно. Это та же логика, но когда ваш мозг перегорел, это может быть трудно увидеть. Еще раз спасибо!

zhn11tau 16.07.2018 12:48

Другие вопросы по теме