[any version] Is there any way to use Twine to generate files?

For example a text file or a midi file?

For the purposes of the question, assume that I know the correct format for such files.

It’s possible using custom Javascript, within browser limitations. You can generate a file and trigger the browser to download it but it works the same way as downloading any other files on the Internet, which means that most of the time the browser either asks the player where the file should be placed or puts it in the downloads folder. You can’t choose the location and you can’t force the download without the player noticing.

For generating text files see e.g. https://gist.github.com/danallison/3ec9d5314788b337b682 (haven’t tested it but looks correct.) You can also adapt that to attach it to a Twine link. For MIDI files you need a Javascript library, but including and using them is a bit more involved.