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.py247 chars11 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.py32 chars2 lines
where read_lines.py
is the name of the script and myfile.txt
is the name of the input file.
gistlibby LogSnag