Edit
Hopefully this can clear up any confusion on why this solution works.
html = request.POST['htmltext']
f = open("tracker/templates/jobs/forms/new_file.html", "wb")
f.write(html.encode('utf-8'))
f.close()
When writing to a file using write(), python uses text mode ("w"). Writing in binary mode ("wb") means that the data will be written in its raw binary form.
By using the encoding standard UTF-8
, you are specifying to convert the string into bytes in the UTF-8 encoding format. This is necessary because it will ensure that non-ASCII characters, such as the newline characters already in your string, are encoded properly.
Previous Answer
When using pythons write() method, it is writing exactly what is provided into the file. So if you attempt to write()
a string which contains a newline character, python will see that it is at the end of a line, and start a newline. This is why you are essentially seeing 2 newlines.
To fix this, strip()
the string to remove extra newline characters from the output file.
f.write(html.strip())