Farhan Ansari
Farhan Ansari

Reputation: 299

How to pass an argument with python on commandline to perform actions on .txt and generate output

How can we program this with python? which lib?

If “program_name input_file column_no pattern” is executed, print the strings from the given column only if the pattern is contained in them.

For example, ./awkward contacts.txt 1 mi

The output will be:

Amit
Pramit

If “program_name input_file column_no ^pattern ” or “program_name input_file column_name pattern$” is executed, print the strings from the given column only if: a) the strings starts with the given pattern (if ^pattern is provided) b) the strings end with the given pattern (if pattern$ is provided)

For example, ./awkward contacts.txt 1 ^Am

The output will be:

Amit

Upvotes: 0

Views: 141

Answers (1)

Leszek Kicior
Leszek Kicior

Reputation: 193

To pass arguments from the command line, try using sys.argv. This will give you a list of arguments used.

For example, let's say example.py contains this code:

import sys
print (sys.argv)

Now, if you execute it with arguments it will give you the list of arguments you passed to it, as strings. The first argument will always be the name of the program:

>>>python example.py arg1 arg2
['example.py', 'arg1', 'arg2']

From there, open the .txt file and use readline() and regular expressions to output only the lines you want.

Upvotes: 1

Related Questions