PYTHON get files from command line PYTHON get files from command line python python

PYTHON get files from command line


A great option is the fileinput module, which will grab any or all filenames from the command line, and give the specified files' contents to your script as though they were one big file.

import fileinputfor line in fileinput.input():    process(line)

More information here.


import sysfilename = sys.argv[-1]

This will get the last argument on the command line. If no arguments are passed, it will be the script name itself, as sys.argv[0] is the name of the running program.


Using argparse is quite intuitive:

import argparseparser = argparse.ArgumentParser()                                               parser.add_argument("--file", "-f", type=str, required=True)args = parser.parse_args()

Now the name of the file is located in:

args.file

You just have to run the program a little differently:

python code.py -f input.txt