Testing a python program by .txt input file

On reading faqs i have seen the following:
How should I test my program?
The best way of testing your program is doing so in exactly the same way that Codechef does. Create an input file (for example, in.txt). Then run your program from the command line, using < and > to redirect the streams. For example:
java test < in.txt > out.txt
or
test.exe < in.txt > out.txt
Your output will then be in the out.txt file, so you can check if it is correct.
Often people forget to print a new line between test cases, but this is easily avoided if you use this method of testing.

HOW TO DO THIS IN PYTHON??? Please Help…

Go through the links below for understanding command-line arguments,file io in python.

link: command line arguments
link: sys.argv
link: file i/o in python-docs

As an example, the code below is a solution to problem link: TEST


    import sys						# to use list argv, argv[0] contains filename
    infile=open(sys.argv[1],"r")    # argv[1] will have input file name, open in read mode
    outfile=open(sys.argv[2],"w")   # argv[2] will have output file name, open in write mode
    while True:
    	x=int(infile.readline())
	    if x!=42:
            outfile.write(str(x)+'\n')  #convert x to str, since write() takes a string parameter
        else:
	        break
    infile.close()
    outfile.close()

Run the file as
python filename.py in.txt out.txt

I hope it helped :slight_smile:

1 Like