By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,354 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

Very simple Python program help...

P: 1
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!
May 7 '07 #1
Share this Question
Share on Google+
3 Replies


bartonc
Expert 5K+
P: 6,596
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:
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.expanduser() and os.path.expandvars().)

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('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
May 7 '07 #2

dshimer
Expert 100+
P: 136
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.
May 7 '07 #3

bvdet
Expert Mod 2.5K+
P: 2,851
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:
Expand|Select|Wrap|Line Numbers
  1. >>> dn = 'directory_path'
  2. >>> 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:
Expand|Select|Wrap|Line Numbers
  1. f = open('file_name', 'w')
  2. f.write(fileStr)
  3. f.close()
May 7 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.