Question Authors' Forum

Python3 write to file

Python3 write to file

by Markus Signitzer -
Number of replies: 1

Dear Richard,
thank you for CodeRunner! It is a great tool :) but I have not yet mastered it :/

I would like to test file I/O with python and I am aware that I can use the "support files" to supply files to the runtime environment of my students.
However I don't know how to test to test when students are supposed to write/create/append a file.
I would like to check:

  • the file name
  • the content of the file
  • if the student closed the file-stream prior to the end of his program
It does not matter to me if the question is of the type "write a function" or "write a program"
Thanks for your help!
Markus
In reply to Markus Signitzer

Re: Python3 write to file

by Richard Lobb -

Here's a screen shot from one of our questions that asks students to read one file and write another file with the order of lines in the file reversed.

Screenshot of file-writing question

As you can see, the test in this case just calls the student's function then checks to see if the new file exists and, if so, prints its contents.

This doesn't however check if the student has closed the file or not.  I haven't found an easy way of doing that. A simple hack is to check for the existence of a substring .close() within the student's code but it's not failsafe - the close() might be of an unrelated file, or in a comment, say.