newb question: file searching

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jaysherby@gmail.com

    #1

    newb question: file searching

    I'm new at Python and I need a little advice. Part of the script I'm
    trying to write needs to be aware of all the files of a certain
    extension in the script's path and all sub-directories. Can someone
    set me on the right path to what modules and calls to use to do that?
    You'd think that it would be a fairly simple proposition, but I can't
    find examples anywhere. Thanks.

  • godavemon

    #2
    Re: newb question: file searching

    Hey, I've done similar things.

    You can use system comands with the following

    import os
    os.system('comm and here')

    You'd maybe want to do something like

    dir_name = 'mydirectory'
    import os
    os.system('ls ' +dir_name + ' lsoutput.tmp')
    fin = open('lsoutput. tmp', 'r')
    file_list = fin.readlines()
    fin.close()

    Now you have a list of all the files in dir_name stored in file_list.

    Then you'll have to parse the input with string methods. They're easy
    in python. Here's the list of them:


    There is probably a better way to get the data from an os.system
    command but i haven't figured it out. Instead what i'm doing is
    writing the stdio output to a file and reading in the data. It works
    fine. Put it in your tmp dir if you're in linux.


    jaysherby@gmail .com wrote:
    I'm new at Python and I need a little advice. Part of the script I'm
    trying to write needs to be aware of all the files of a certain
    extension in the script's path and all sub-directories. Can someone
    set me on the right path to what modules and calls to use to do that?
    You'd think that it would be a fairly simple proposition, but I can't
    find examples anywhere. Thanks.

    Comment

    • godavemon

      #3
      Re: newb question: file searching

      Hey, I've done similar things.

      You can use system comands with the following

      import os
      os.system('comm and here')

      You'd maybe want to do something like

      dir_name = 'mydirectory'
      import os
      os.system('ls ' +dir_name + ' lsoutput.tmp')
      fin = open('lsoutput. tmp', 'r')
      file_list = fin.readlines()
      fin.close()

      Now you have a list of all the files in dir_name stored in file_list.

      Then you'll have to parse the input with string methods. They're easy
      in python. Here's the list of them:


      There is probably a better way to get the data from an os.system
      command but i haven't figured it out. Instead what i'm doing is
      writing the stdio output to a file and reading in the data. It works
      fine. Put it in your tmp dir if you're in linux.


      jaysherby@gmail .com wrote:
      I'm new at Python and I need a little advice. Part of the script I'm
      trying to write needs to be aware of all the files of a certain
      extension in the script's path and all sub-directories. Can someone
      set me on the right path to what modules and calls to use to do that?
      You'd think that it would be a fairly simple proposition, but I can't
      find examples anywhere. Thanks.

      Comment

      • Mike Kent

        #4
        Re: newb question: file searching


        jaysherby@gmail .com wrote:
        I'm new at Python and I need a little advice. Part of the script I'm
        trying to write needs to be aware of all the files of a certain
        extension in the script's path and all sub-directories.
        What you want is os.walk().



        Comment

        • hiaips

          #5
          Re: newb question: file searching

          jaysherby@gmail .com wrote:
          I'm new at Python and I need a little advice. Part of the script I'm
          trying to write needs to be aware of all the files of a certain
          extension in the script's path and all sub-directories. Can someone
          set me on the right path to what modules and calls to use to do that?
          You'd think that it would be a fairly simple proposition, but I can't
          find examples anywhere. Thanks.
          dir_name = 'mydirectory'
          extension = 'my extension'
          import os
          files = os.listdir(dir_ name)
          files_with_ext = [file for file in files if file.endswith(e xtension)]

          That will only do the top level (not subdirectories) , but you can use
          the os.walk procedure (or some of the other procedures in the os and
          os.path modules) to do that.

          --Dave

          Comment

          • jaysherby@gmail.com

            #6
            Re: newb question: file searching

            Mike Kent wrote:I'm thinking os.walk() could definitely be a big part of my solution,
            but I need a little for info. If I'm reading this correctly, os.walk()
            just goes file by file and serves it up for your script to decide what
            to do with each one. Is that right? So, for each file it found, I'd
            have to decide if it met the criteria of the filetype I'm searching for
            and then add that info to whatever datatype I want to make a little
            list for myself? Am I being coherent?

            Something like:

            for files in os.walk(top, topdown=False):
            for name in files:
            (do whatever to decide if criteria is met, etc.)

            Does this look correct?

            Comment

            • hiaips

              #7
              Re: newb question: file searching

              I'm thinking os.walk() could definitely be a big part of my solution,
              but I need a little for info. If I'm reading this correctly, os.walk()
              just goes file by file and serves it up for your script to decide what
              to do with each one. Is that right? So, for each file it found, I'd
              have to decide if it met the criteria of the filetype I'm searching for
              and then add that info to whatever datatype I want to make a little
              list for myself? Am I being coherent?
              >
              Something like:
              >
              for files in os.walk(top, topdown=False):
              for name in files:
              (do whatever to decide if criteria is met, etc.)
              >
              Does this look correct?
              IIRC, repeated calls to os.walk would implement a depth-first search on
              your current directory. Each call returns a list:
              [<directory name relative to where you started>, <list of files and
              directories in that directory>]

              --dave

              Comment

              • jaysherby@gmail.com

                #8
                Re: newb question: file searching

                Thanks, Dave. That's exactly what I was looking for, well, except for
                a few small alterations I'll make to achieve the desired effect. I
                must ask, in the interest of learning, what is

                [file for file in files if file.endswith(e xtension)]

                actually doing? I know that 'file' is a type, but what's with the set
                up and the brackets and all? Can someone run down the syntax for me on
                that? And also, I'm still not sure I know exactly how os.walk() works.
                And, finally, the python docs all note that symbols like . and ..
                don't work with these commands. How can I grab the directory that my
                script is residing in?

                Thanks.


                hiaips wrote:
                jaysherby@gmail .com wrote:
                I'm new at Python and I need a little advice. Part of the script I'm
                trying to write needs to be aware of all the files of a certain
                extension in the script's path and all sub-directories. Can someone
                set me on the right path to what modules and calls to use to do that?
                You'd think that it would be a fairly simple proposition, but I can't
                find examples anywhere. Thanks.
                >
                dir_name = 'mydirectory'
                extension = 'my extension'
                import os
                files = os.listdir(dir_ name)
                files_with_ext = [file for file in files if file.endswith(e xtension)]
                >
                That will only do the top level (not subdirectories) , but you can use
                the os.walk procedure (or some of the other procedures in the os and
                os.path modules) to do that.
                >
                --Dave

                Comment

                • Jason

                  #9
                  Re: newb question: file searching


                  jaysherby@gmail .com wrote:
                  Mike Kent wrote:>
                  I'm thinking os.walk() could definitely be a big part of my solution,
                  but I need a little for info. If I'm reading this correctly, os.walk()
                  just goes file by file and serves it up for your script to decide what
                  to do with each one. Is that right? So, for each file it found, I'd
                  have to decide if it met the criteria of the filetype I'm searching for
                  and then add that info to whatever datatype I want to make a little
                  list for myself? Am I being coherent?
                  >
                  Something like:
                  >
                  for files in os.walk(top, topdown=False):
                  for name in files:
                  (do whatever to decide if criteria is met, etc.)
                  >
                  Does this look correct?
                  Not completely. According to the documentation, os.walk returns a
                  tuple:
                  (directory, subdirectories, files)
                  So the files you want are in the third element of the tuple.

                  You can use the fnmatch module to find the names that match your
                  filename pattern.

                  You'll want to do something like this:
                  >>for (dir, subdirs, files) in os.walk('.'):
                  .... for cppFile in fnmatch.filter( files, '*.cpp'):
                  .... print cppFile
                  ....
                  ActiveX Test.cpp
                  ActiveX TestDoc.cpp
                  ActiveX TestView.cpp
                  MainFrm.cpp
                  StdAfx.cpp
                  >>>
                  Please note that your results will vary, of course.

                  Comment

                  • hiaips

                    #10
                    Re: newb question: file searching


                    jaysherby@gmail .com wrote:
                    Thanks, Dave. That's exactly what I was looking for, well, except for
                    a few small alterations I'll make to achieve the desired effect. I
                    must ask, in the interest of learning, what is
                    >
                    [file for file in files if file.endswith(e xtension)]
                    >
                    actually doing? I know that 'file' is a type, but what's with the set
                    up and the brackets and all? Can someone run down the syntax for me on
                    that? And also, I'm still not sure I know exactly how os.walk() works.
                    And, finally, the python docs all note that symbols like . and ..
                    don't work with these commands. How can I grab the directory that my
                    script is residing in?
                    [file for file in files if file.endswith(e xtension)] is called a list
                    comprehension. Functionally, it is equivalent to something like this:
                    files_with_ext = []
                    for file in files:
                    if file.endswith(e xtension):
                    files_with_ext. append(file)
                    However, list comprehensions provide a much more terse, declarative
                    syntax without sacrificing readability.

                    To get your current working directory (i.e., the directory in which
                    your script is residing):
                    cwd = os.getcwd()

                    As far as os.walk...
                    This is actually a generator (effectively, a function that eventually
                    produces a sequence, but rather than returning the entire sequence, it
                    "yields" one value at a time). You might use it as follows:
                    for x in os.walk(mydirec tory):
                    for file in x[1]:
                    <whatever tests or code you need to run>

                    You might want to read up on the os and os.path modules - these
                    probably have many of the utilities you're looking for.

                    Good luck,
                    dave

                    Comment

                    • hiaips

                      #11
                      Re: newb question: file searching

                      Oops, what I wrote above isn't quite correct. As another poster pointed
                      out, you'd want to do
                      for file in x[2]:
                      ....

                      --dave

                      Comment

                      • jaysherby@gmail.com

                        #12
                        Re: newb question: file searching

                        So far, so good. I just have a few more questions.

                        Here's my code so far:

                        import os
                        top = '/home/USERNAME/'
                        images = []
                        for files in os.walk(top, topdown=True):
                        images += [file for file in files[2] if file.endswith(' jpg')]
                        print images

                        I still need to know how I can dynamically get the name of the
                        directory that my script is in. Also, how can I get it to add the full
                        path of the file to "images" instead of just the file name. See, when
                        I go to use a particular image name later on, it won't do me much good
                        if I don't have the path to it.

                        Comment

                        • Simon Forman

                          #13
                          Re: newb question: file searching

                          jaysherby@gmail .com wrote:
                          hiaips wrote:
                          jaysherby@gmail .com wrote:
                          I'm new at Python and I need a little advice. Part of the script I'm
                          trying to write needs to be aware of all the files of a certain
                          extension in the script's path and all sub-directories. Can someone
                          set me on the right path to what modules and calls to use to do that?
                          You'd think that it would be a fairly simple proposition, but I can't
                          find examples anywhere. Thanks.
                          dir_name = 'mydirectory'
                          extension = 'my extension'
                          import os
                          files = os.listdir(dir_ name)
                          files_with_ext = [file for file in files if file.endswith(e xtension)]

                          That will only do the top level (not subdirectories) , but you can use
                          the os.walk procedure (or some of the other procedures in the os and
                          os.path modules) to do that.

                          --Dave
                          >
                          Thanks, Dave. That's exactly what I was looking for, well, except for
                          a few small alterations I'll make to achieve the desired effect. I
                          must ask, in the interest of learning, what is
                          >
                          [file for file in files if file.endswith(e xtension)]
                          >
                          actually doing? I know that 'file' is a type, but what's with the set
                          up and the brackets and all? Can someone run down the syntax for me on
                          that? And also, I'm still not sure I know exactly how os.walk() works.
                          And, finally, the python docs all note that symbols like . and ..
                          don't work with these commands. How can I grab the directory that my
                          script is residing in?
                          >
                          Thanks.
                          >
                          >
                          'file' *is* the name of the file type, so one shouldn't reuse it as the
                          name of a variable as Dave did in his example.

                          the brackets are a "list comprehension" and they work like so:

                          files_with_ext = []
                          for filename in files:
                          if filename.endswi th(extension):
                          files_with_ext. append(filename )

                          The above is exactly equivalent to the [filename for filename in
                          files... ] form.

                          AFAIK, os.listdir('.') works fine, but you can also use
                          os.listdir(os.g etcwd()). However, both of those return the current
                          directory, which can be different than the directory your script's
                          residing in if you've called os.chdir() or if you start your script
                          from a different directory.
                          HTH.

                          (Also, if you're not already, be aware of os.path.isfile( ) and
                          os.path.isdir() . They should probably be helpful to you.)

                          Peace,
                          ~Simon

                          Comment

                          • Steve M

                            #14
                            Re: newb question: file searching


                            jaysherby@gmail .com wrote:
                            I must ask, in the interest of learning, what is
                            >
                            [file for file in files if file.endswith(e xtension)]
                            >
                            actually doing? I know that 'file' is a type, but what's with the set
                            up and the brackets and all?
                            Other people explained the list comprehension, but you might be
                            confused about the unfortunate choice of 'file' as the name in this
                            example. 'file' is a built-in as you remarked. It is allowed, but a bad
                            idea, to use names that are the same as built-ins. Some people
                            characterize this as shadowing the built-in.

                            A similar, common case is when people use the name 'list' for a list
                            object. They shouldn't.

                            The example could have been written as:

                            [f for f in files if f.endswith(exte nsion)]

                            Comment

                            • jaysherby@gmail.com

                              #15
                              Re: newb question: file searching

                              Okay. This is almost solved. I just need to know how to have each
                              entry in my final list have the full path, not just the file name.
                              Also, I've noticed that files are being found within hidden
                              directories. I'd like to exclude hidden directories from the walk, or
                              at least not add anything within them. Any advice?

                              Here's what I've got so far:

                              def getFileList():
                              import os
                              imageList = []
                              for files in os.walk(os.getc wd(), topdown=True):
                              imageList += [file for file in files[2] if file.endswith(' jpg') or
                              file.endswith(' gif')]
                              return imageList

                              Comment

                              Working...