writelines writes a sequence of strings to a file object consecutively. Despite its name, it does not add newline characters; strings become separate lines only when they already contain newlines. section 13.4
Keep these rules in mind:
- Pass a list of strings, such as ["first\n", "second\n"]. Each string is written unchanged in sequence. section 13.4
- Do not expect automatic line breaks: strings without trailing newlines are effectively concatenated. section 13.4
- Use write for one string; use writelines when handling a list returned by readlines or another sequence of strings. section 13.4
- Text-mode newline translation can map \n to platform-specific line endings; specify open(..., newline=...) when exact treatment matters. section 13.4
Copy lines without changing their endings
Open the source with newline="" so its original line endings are returned, read the strings, then pass them directly to writelines: lines = input_file.readlines(); output.writelines(lines). Because each returned string retains its ending, the output can be identical to the input. section 13.4
Writing to standard output
sys.stdout behaves as a specialized file object, so sys.stdout.writelines(["A first line.\n", "A second line.\n"]) writes both lines. Redirecting sys.stdout to a file sends the same output there. section 13.6
input_file = open("myfile.txt", 'r', newline="")
lines = input_file.readlines()
input_file.close()
output = open("myfile2.txt", 'w')
output.writelines(lines)
output.close()
Walk through a complete read-and-copy example using readlines, newline="", and writelines. section 13.4
