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?
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
John Constantine
  • 1,038
  • 4
  • 15
  • 43

3 Answers3

5

1 + 2. Shell redirection.

$ python foo.py < input.txt > output.txt
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
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
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186