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!
Very simple Python program help...
Collapse
X
-
Tags: None
-
Originally posted by footloose61I 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!
Originally posted by 2.4 docs6.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'] -
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
-
Originally posted by dshimerDepending 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.Code:>>> dn = 'directory_path' >>> fileStr = '\n'.join([f for f in os.listdir(dn) if os.path.isfile(os.path.join(dn, f))])
Code:f = open('file_name', 'w') f.write(fileStr) f.close()
Comment
Comment