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?
In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys.argv) will store all the information in the command line entry and can be accessed inside the Python script. Python’s getopt module can also be used to parse named arguments. Let’s go through some examples.
One approach is to parameterize some of the variables originally hard coded in the script, and pass them as arguments to your script. If you have only 1 or 2 arguments, you may find sys.argv is good enough since you can easily access the arguments by the index from argv list.
Argument Parsing in Python Python Server Side Programming Programming Every programming language has a feature to create scripts and run them from the terminal or being called by other programs. When running such scripts we often need to pass on arguments needed by the script for various functions to be executed inside the script.
# Print arguments one by one print('First argument:', str(sys.argv[0])) print('Second argument:', str(sys.argv[1])) print('Third argument:', str(sys.argv[2])) print('Fourth argument:', str(sys.argv[3])) Then execute the above script with command line parameters. python script.py first 2 third 4.5 You will see the results like below.
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
In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself.
Vinko is right: the glob module does the job:
import glob, sys
for arg in glob.glob(sys.argv[1]):
print "Arg:", arg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With