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

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.

1

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
1

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>

0
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest