Input the Filename in the Commandline as an Argument in Python [Closed]
I Want to Do the Modification in My Code Such That I Am Able to Input My File in the Same Command Line Where I’m Calling Python Code Like: Script. Py Filename...
I want to do the modification in my code such that I am able to input my file in the same command line where I’m calling python code like:
script.py filename
Presently my code is:
filename = raw_input('Enter a filename: ')
with open(filename) as f:
next(f)
for lines in f:
Please suggest me how should I proceed with the same.
3 Answers
I would use sys.argv.
import sys
filename = sys.argv[1]
sys.argv will be a list of elements in your call.
sys.argv is the easiest for a simple use case.
For more advanced uses you could use argparse, but I'd prefer click (“Command Line Interface Creation Kit”) which makes creating command line tools with Python really easy:
import click
@click.command()
@click.argument('filename', type=click.Path(exists=True, readable=True), nargs=1)
def main(filename):
...
main()
using @click.option() you can also create custom flags such as --filename.
This makes using arguments much easier, as you can define input types that get checked automatically. It also produces nice error messages and with --help it prints usage information:
Usage: test.py [OPTIONS] FILENAME
Options:
--help Show this message and exit.
You will need to install click:
# Python2:
pip install click
# Python3:
pip3 install click
Use sys module:
import sys
with open(sys.argv[1]) as filename:
for line in filename:
print(line)
See also How to read/process command line arguments? for usage of argparse module to create custom flags such as -f <filename>