read lines from file with argument parser in python

To read lines from a file using argument parser in Python, we can use the built-in argparse module. Here's an example code using argparse and with open to read the file:

main.py
import argparse

parser = argparse.ArgumentParser(description='Read lines from file')
parser.add_argument('filename', help='Input file name')

args = parser.parse_args()

with open(args.filename) as file:
    for line in file:
        print(line)
247 chars
11 lines

Here, we define an argument parser with a positional argument filename which takes the name of the input file. Then, we parse the command line arguments to get the filename provided by the user. We use with open to open the file and read its contents line by line. Finally, we print each line to the console.

You can run the script by calling it from the command line as follows:

main.py
python read_lines.py myfile.txt
32 chars
2 lines

where read_lines.py is the name of the script and myfile.txt is the name of the input file.

gistlibby LogSnag