Passing arguments with wildcards to a Python script

Issue

I want to do something like this:

c:\data\> python myscript.py *.csv

and pass all of the .csv files in the directory to my python script (such that sys.argv contains ["file1.csv", "file2.csv"], etc.)

But sys.argv just receives ["*.csv"] indicating that the wildcard was not expanded, so this doesn’t work.

I feel like there is a simple way to do this, but can’t find it on Google. Any ideas?

Solution

You can use the glob module, that way you won’t depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards 🙂 ).

from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument

Answered By – Vinko Vrsalovic

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published