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?
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]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With