How to read JUST filenames of a directory in python and then do the same job for all?
Question: I have a python script which has this line at the very beginning to read from
an input data file:

    
    
        x,y = genfromtxt('data1.txt').T
    

Then I proceed and do the processing on x,y (it depends on a fixed parameter
e.g n=5). Finally I generate the output file with this line

    
    
        with open('output_data1_n{0}.txt'.format(num),'wb') as file: 
    

This gives me output_data1_n5.txt and write the xnew and ynew on it.

Question: I have a directory with many txt files! How can I systematically do
this job for all files in that directory instead of running by hand for each
input file?

It should be like: get the txt files (e.g with os.walk ?) as a string and
replace it to input, then generate the output name including the parameter n.

I appreciate your suggestions.


Answer: Try the [`glob` module](http://docs.python.org/2/library/glob.html).

It lets you get a list of file names in a directory with some wild cards.

Example:

    
    
    from glob import glob
    from os import path
    
    def get_files_in(folder, pattern='*.txt'):
        return glob(path.join(folder, pattern))
    

Usage:

    
    
    get_files_in('C:/temp') # files in C:/temp that are ending with .txt
    get_files_in('C:/temp', '*.xml') # files in C:/temp that are ending with .xml
    get_files_in('C:/temp', 'test_*.csv') # files in C:/temp that start with test_ and end in .csv
    

