简体   繁体   中英

Python textwrap: different results for terminal print vs. write to file

I have been experimenting with the Python textwrap module, to wrap long lines of text. I noticed that the print output to terminal looks fine, the word wrap works as expected. But when I write to file, slightly different output is seen. Is this a known feature of print vs. write, I wonder?

import os, sys
import textwrap

INFILE="in.txt"
OUTFILE="out.txt"

with open(INFILE, 'r') as file:
  lines = file.readlines()
  for line in lines:
    print(textwrap.fill(line, width=42))
    # works as expected

with open(OUTFILE, 'w') as fp:
 for l in lines:
   fp.write(textwrap.fill(l, width=42))
   # not the same output is written to file

in.txt:

As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application.

GNU LESSER GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.

I ended up using this code. It uses print() and sends the output to a file and works well.

       print("Wrapping lines..."+myfile) 
       for l in lines:
           print(textwrap.fill(l, width=80),file=fp)```


Yes, there is a difference between print() and write() . Several: Here they are:

  • print()
    • is a built-in global function
    • by default outputs to the stdout (but can be changed with the fp= arg).
    • by default adds a newline ( \n ) to each string (but can be changed with the end= arg).
  • write()
    • is a method (bound function) of a file object
    • outputs only on that file object
    • does not add a newline; you have to do that yourself by expressly adding the newline to the string, or inserting an extra fp.write("\n") after your write statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM