Get a file from CLI input

PythonInputCommand

Python Problem Overview


How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:

python code.py input.txt

so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a pretty vague question, but I don't really know how to explain it any better.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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
              

Solution 4 - Python

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.

Solution 5 - Python

I also like argparse, it's clean, simple, fairly standard, gives free error handling, and add a [-h] option to help the user.

Here is a version that do not need the named parameters, which may be annoying for a very simple script:

#!/usr/bin/python3

import argparse
    
arg_parser = argparse.ArgumentParser( description = "Copy source_file as target_file." )
arg_parser.add_argument( "source_file" )
arg_parser.add_argument( "target_file" )
arguments = arg_parser.parse_args()

source = arguments.source_file
target = arguments.target_file
print( "Copying [{}] to [{}]".format(source, target) )

Example of how it handles errors and help for you:

>my_test.py

usage: my_test.py [-h] source_file target_file
my_test.py: error: the following arguments are required: source_file, target_file

>my_test.py my_source.cpp

usage: my_test.py [-h] source_file target_file
my_test.py: error: the following arguments are required: target_file

>my_test.py -h

usage: .py [-h] source_file target_file

Copy source_file as target_file.

positional arguments:
  source_file
  target_file

optional arguments:
  -h, --help   show this help message and exit

>my_test.py my_source.cpp my_target.cpp

Copying [my_source.cpp] to [my_target.cpp]

Solution 6 - Python

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

Solution 7 - Python

In addition to what is mentioned by the already existing answers, there is an other alternative relying on the use of Command Line Interface Creation Kit (Click). Its latest stable version by the time I posted this answer is version 6. The official documentation has examples on how to deal with files and pass them as command line arguments.

Solution 8 - Python

Just use the basic command raw_input

declare input file name as string

inFile = ""
inFile = raw_input("Enter the input File Name: ")

Now you can open the file by using with open(inFile,'w')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNaveen C.View Question on Stackoverflow
Solution 1 - PythonkindallView Answer on Stackoverflow
Solution 2 - PythonagfView Answer on Stackoverflow
Solution 3 - PythonDegrawView Answer on Stackoverflow
Solution 4 - PythonMark TolonenView Answer on Stackoverflow
Solution 5 - PythonGroo the bug slayerView Answer on Stackoverflow
Solution 6 - PythonSohail ShaukatView Answer on Stackoverflow
Solution 7 - PythonBillal BegueradjView Answer on Stackoverflow
Solution 8 - PythonRajeev KumarView Answer on Stackoverflow