Very simple Python program help...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • footloose61
    New Member
    • May 2007
    • 1

    Very simple Python program help...

    I am extremely new to python and I need to write a program that simply outputs all the filenames within a specific directory to a text file. Thanks!
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by footloose61
    I am extremely new to python and I need to write a program that simply outputs all the filenames within a specific directory to a text file. Thanks!
    The glob module may be what you are looking for:
    Originally posted by 2.4 docs
    6.24 glob -- Unix style pathname pattern expansion

    The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch () functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, use os.path.expandu ser() and os.path.expandv ars().)

    For example, consider a directory containing only the following files: 1.gif, 2.txt, and card.gif. glob() will produce the following results. Notice how any leading components of the path are preserved.

    >>> import glob
    >>> glob.glob('./[0-9].*')
    ['./1.gif', './2.txt']
    >>> glob.glob('*.gi f')
    ['1.gif', 'card.gif']
    >>> glob.glob('?.gi f')
    ['1.gif']

    Comment

    • dshimer
      Recognized Expert New Member
      • Dec 2006
      • 136

      #3
      Depending on what you want to do, once you get all the filenames into a list using glob you may also find some help in parsing filenames into individual parts (drive, path, base name, extension) using the os.path module. I find these two modules to be a huge help in working with file names.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by dshimer
        Depending on what you want to do, once you get all the filenames into a list using glob you may also find some help in parsing filenames into individual parts (drive, path, base name, extension) using the os.path module. I find these two modules to be a huge help in working with file names.
        There are a several threads on the Python forum on compiling a list of file names from a specific directory. In short, the file list can be created like this:
        Code:
        >>> dn = 'directory_path'
        >>> fileStr = '\n'.join([f for f in os.listdir(dn) if os.path.isfile(os.path.join(dn, f))])
        Directory listings are skipped in the above list comprehension. To write the resulting string to a disk file:
        Code:
        f = open('file_name', 'w')
        f.write(fileStr)
        f.close()

        Comment

        Working...