A newline character marks the boundary between lines of text. In Python, it is represented by \n and is normally included at the end of each line returned while iterating over a text file. A blank line therefore contains one newline character. section 6.3 section 6.11
Line endings vary by operating system: Unix uses LF, Windows uses CR+LF, and old-style Macs used CR. Python usually translates these forms while reading and selects the platform-appropriate form while writing. section 6.18
Handle newlines deliberately when processing files:
- Use str.rstrip() before reversing or otherwise transforming a line when the newline should not be part of the content. section 6.27
- Add \n when writing transformed content that must remain on its own line. section 6.27
- Do not assume every file ends with a newline; the final line may stop immediately at end-of-file. section 6.3
- Use open(..., newline='\n') or newline='\r\n' when automatic line-ending translation produces incorrect output. section 6.18
Reverse each line without reversing its newline
with open(input_file) as source, open(output_file, 'w') as destination:\n for line in source:\n destination.write(line.rstrip()[::-1] + '\n')\n\nFor input containing "abc def\nghi jkl\n", the transformed content is "fed cba\nlkj ihg\n". The newline stays at the line boundary while the remaining characters are reversed. section 6.26 section 6.27
abc def ghi jkl
Inspect the input lines used for the reverse-lines transformation. section 6.26
fed cba lkj ihg
Compare the output after reversing line content while preserving line boundaries. section 6.26





