Python: loop through several csv files
Question: I was wondering if anybody knew how I could change a script in Python so it
goes through a folder containing csv files and takes them in groups of three.
The script is working when I type the file names in the command line, but I've
got lots of files, so that would take forever. It looks like this now:

    
    
    resultsdir = "blah"
    
    #filename1=sys.argv[1]
    #filename2=sys.argv[2]
    #filename3=sys.argv[3]
    
    file1 = open(resultsdir+"/"+filename1+".csv")
    file2 = open(resultsdir+"/"+filename2+".csv") 
    file3 = open(resultsdir+"/"+filename3+".csv")
    

I'm a complete beginner, I hope I've been able to explain what I want. Cheers
for any help!


Answer: You could use the `glob` module
(<http://docs.python.org/3.3/library/glob.html>) to get all `.csv` files in a
directory and open them then.

**Example:**

    
    
    import glob
    resultsdir = "blah"
    
    files = sorted(glob.glob(resultsdir+'/*.csv'))
    while len(files) >= 3:
         file1 = open(files.pop(0))
         file2 = open(files.pop(0))
         file3 = open(files.pop(0))
         # Do something
    # if the number of files can't be divided by 3 do something
    # with the 1 or 2 files which are left
    

**Edit:** Changed `files.pop()` to `files.pop(0)` to get the files from the
first to the last and not from the last to the first file.

