PageWidth not inserting line breaks into long strings

I am having some trouble setting the width of my output. I have some very long expressions, and I would like to output them as strings of maximum length 80 characters. For example, I have a very long expression "beta" and I would like to output to a file "RGEs_nicks.txt". So I have tried

streamM = OpenWrite["RGEs_nicks.txt", PageWidth -> 80];
WriteString[streamM, ToString[beta // InputForm]];
Close[streamM];


However, this is not putting in any line breaks, and the output is just one very long line. How do I get this to be formatted output? It works fine if I use just Write instead of WriteString, but I want to be able to add some other tricky stuff before and after so I need the WriteString. Any clues would be much appreciated!

• Probably #<>"\n"&/@StringPartition[ToString[beta // InputForm],UpTo[80]] is what you need? – Alx Jul 29 '19 at 10:55
• Thanks @Alx! However, this is not quite what I want, because I think this might break the string into pieces where things should not be split, for example in the middle of a variable. Might this happen? – Nick Murphy Jul 29 '19 at 15:34
• Well, this might happen. Another idea: first determine positions of, e.g., spaces: StringPosition[ToString[beta // InputForm], " "]. Then choose from that positions those near to desired length of multiples of 80, and StringInsert[ToString[beta // InputForm], "\n", {<positions>}]. – Alx Jul 29 '19 at 16:01
• What tricky stuff causes you to need to use WriteString? – Carl Woll Jul 30 '19 at 19:58

Assuming you really need to use WriteString for some reason, you could use ExportString, which respects PageWidth, to do the formatting for you:
streamM = OpenWrite["RGEs_nicks.txt"];

The advantage of using ExportString is that it knows how to preserve a valid syntax when doing the line wrapping, as opposed to blind string splitting.