遍历Python中的许多目录[Python3]

时间:2018-07-13 08:33:22

标签: python python-3.x loops

因此,我一直在研究一个程序,该程序需要遍历特定目录中的每个文件,并根据文件执行操作。该位已经完成(下面的代码),但是我确实需要扩展它,以便我可以根据需要解析多个目录,并使程序按顺序循环遍历它们。我的代码如下(对于非常笨拙的错误代码,我们深表歉意):

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 )

1 个答案:

答案 0 :(得分:0)

这是在不同目录中运行逻辑的方法:

>>> 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)
...
相关问题