How can I preserve line endings when reading and writing a text file?
Quick answer
In Python, open a copied text file with newline='' when reading so \n, \r, and \r\n are returned untranslated. Keep those endings in the text, and open the output with newline='' too, so writing does not translate \n characters. Choose an encoding appropriate for the sample, and inspect the output’s line endings afterward. Reading with untranslated endings alone is not enough if later code changes or normalizes them. [S1]
The question, the details, the next step.
A practical checklist
Make a separate working copy; do not test on the only original.
Choose an encoding appropriate to the copied sample.
Read with
newline=''so recognized endings are returned untranslated.Keep the original ending characters while making the intended text edit.
Write with
newline=''to disable output newline translation.Read the input copy and output with
newline='', then comparerepr()output or ending counts.
A few more useful answers
Does `newline=''` automatically preserve every aspect of the file?
No. It prevents newline translation in text I/O, but your code can still alter endings, and text encoding is a separate consideration. The described approach is not a guarantee of byte-for-byte preservation. [S1]
Why not use the default newline setting for both operations?
With newline=None, reading converts recognized endings to \n, and writing translates \n to the system line separator. That can lose distinctions in a mixed-ending sample. [S1]
When would binary I/O be more appropriate?
Use it when you need byte-level control rather than text-level newline handling. This guide’s text example does not show how to perform or verify a byte-preserving edit. [S1]
Sources
References used for this guide.
- [S1] Python 3.15 io — Core tools for working with streams docs.python.org · Checked
