4

In coding contests, I am supplied an initialization file from which to read initial parameters. However, sometimes the parameters are spread over separate lines as follows:

x
a 
b

(All of them integers)

Now when I read line1, I believe I would store x like this:

x = int(sys.argv[1])

How do I take care of other lines? Will sys.argv[2] give me the next parameter on line 2?

More precisely, will using:

par_list = sys.argv[1:].split(" ") 

give me a list of parameters on all the lines?

2 Answers 2

4

This will do the trick:

>> python program.py $(cat input.txt)

Sample program:

import sys
paras = [int(x) for x in sys.argv[1:]]
print(paras)

Sample input file:

42
-1
100

Output:

>> python program.py $(cat input.txt)
[42, -1, 100]
Sign up to request clarification or add additional context in comments.

1 Comment

This only works in unix environments, and would not work on windows systems. @arvindch's answer should be the one accepted.
3

I'm assuming you're passing the input filename to the python script, in cmdline.

python script.py input.txt

In which case, sys.argv[1] = 'input.txt' is to access the contents of the input file:

with open(sys.argv[1], 'r') as f:
    lines = f.readlines()

Now, lines is a list containing all the lines of data from input.txt.

1 Comment

Yes, that seems to be what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.