0

I have a text file of the format:

2
1 3
2 4

I have written a python program that asks for number of inputs and prints out the values sum .

n = int(raw_input())
for _ in range(n):
     a,b = map(int,raw_input().split())
     print a+b

But

  1. How should I take input from file such that first line is number of test cases and next lines are inputs?
  2. Print the output to a file?

3 Answers 3

5

1 + 2. Shell redirection.

$ python foo.py < input.txt > output.txt
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your input comes from a file, inp.txt, like:

$ cat inp.txt 
2
1 3
2 4

You can use the code below, which basically reads the input file line by line, and computes the values and stores them:

with open("inp.txt", "r") as inp, open("out.txt", "w") as out:
    no_of_cases = int(inp.readline())
    for line in inp:
        a,b = map(int,line.split())
        out.write("%s\n" % (a + b))

Note that no_of_cases has not been used in the code anywhere above because it is redundant for this example.

This will produce the output file out.txt for you, with following data:

$ cat out.txt 
4
6

Comments

1

You can use the fileinput module to make your script support both reading input from a file and reading from stdin.

import fileinput
num_inputs = None
for line in fileinput.input():
    if num_inputs is None:
        num_inputs = int(line)
    else:
        a,b = map(int, line.split())
        print a+b

This way, if you pass a filename as an argument to your script, it reads from it, else it reads from stdin.

Note that in this snippet I just read all the inputs in file after the first line, and make no real use of the num_inputs variable, but you can easily change that to enforce the expected number of inputs is actually read.

As to writing to a file, this is a basic python question, which has already been answered here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.