Question #127249

How to make a script file and a plain text output file (.txt) that contains the test output?

Expert's answer

Since you did not provide any specific case, I'll lay out some general cases. Ask for any clarifications.


The Python-only way

  • A modern Python installation comes with the IDLE IDE. Launch IDLE.
  • Go to File > New File. This will create a new file.
  • Write your code.

For writing output to a file, use the following code snippet:

with open('filename') as f:
    f.writelines(["first line", "second line"])  # the argument must be a list of strings


The un-Python way

Write your code the normal way, taking input and writing output the normal way. Run the code as:

python yourscript.py < inputfile.txt > outputfile.txt

The inputfile.txt is for your optional input and outputfile.txt will contain your (test) output. This is called I/O Redirection (https://linuxcommand.org/lc3_lts0070.php).


unittest

If you are using unittest, write your test file.

class MyTest(unittest.TestCase):  # should be a subclass of TestCase
    def test_foo(self):
        self.assertEqual('first', 'second')  # OK if both are equal
        self.assertTrue(True)  # OK if argument is false. Similarly, you've assertFalse

You can use the command line to run

python -m unittest testfile
python -m unittest testfile.TestClass
python -m unittest testfile.TestClass.test_method

This will run the specific test cases. You can use I/O redirection as before to write output to a file.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS