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 fileinput
for line in fileinput.input():
    process(line)

More information here.


import sys
filename = 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 argparse
parser = 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

Command line parameters are available as a list via the sys module's argv list. The first element in the list is the name of the program (sys.argv[0]). The remaining elements are the command line parameters.

See also the getopt, optparse, and argparse modules for more complex command line parsing.


If you're using Linux or Windows PowerShell you could pipe " | " it after using cat on input.txt file, suppose you have input.txt file and your code.py file in same directory you could use:

cat input.txt | python code.py

This will provide python input from STDIN. for example: if for example you're trying get names from input.txt file

input.txt has

john,matthew,peter,albert

code.py has

print(" is not ".join(input().rstrip().split(',')))

would give

john is not matthew is not peter is not albert