MSIT

Ask to read a file

Tell the model the file name, to open it, to read the text, and to close it. note.txt stays as the lesson wrote it.

What the prompt must say

The box under the question is your prompt. Ask sends that prompt. The model writes into reader.py. Run then checks message. Ask itself does not grade the function.

A useful prompt names four things.

  • The function name, message.
  • The file name, note.txt, a single segment with no slash.
  • The actions: open, read the whole text, and close.
  • The return value: the text that was in the file, not the file name.

The Input and output chapter is the same reference you used by hand. You can ask for encoding="utf-8" and for a with statement. A with statement closes the file when the block ends, so you do not have to remind the model with a separate close line if you asked for with.

A worked example

You want message to return Hello, because that is the text already in note.txt. A short prompt is enough when the four points above are clear.

  1. Name the function: message.
  2. Name the file: note.txt.
  3. Ask it to open that file, read the whole text, and close the file.
  4. Ask it to return that text.

This prompt is one way to say that:

A matching function looks like the one you wrote by hand:

read returns "Hello". That is the value the check compares. If the model returns the string "note.txt", the check fails. Change the prompt so it says to return the text inside the file, then ask again. You may also edit the code yourself.

open() returns a file object, and is most commonly used with two positional arguments: open(filename, mode)

— Python tutorial, Reading and writing files

Do not ask the model to create a new file, to change note.txt, or to read a name with a slash. The kept file stays as the lesson wrote it.

If the check fails, say "return the text in the file" and ask again.

What should you put in the prompt?

Match each part of the prompt with what it tells the model.

  • message
  • note.txt
  • return the text

Exercise

Ask for a function named message that opens note.txt, reads the whole text, closes the file, and returns that text. Leave note.txt as it is.

Ask for a function named message that opens note.txt, reads the whole text, closes the file, and returns that text.

Output