Python textwrap:终端打印与写入文件的结果不同

Python textwrap:终端打印与写入文件的结果不同,python,word-wrap,Python,Word Wrap,我一直在试验Python textwrap模块,以包装长行文本。 我注意到终端的打印输出看起来很好,换行符工作正常。但当我写入文件时,会看到略有不同的输出。 我想知道,这是印刷与书写的一个已知特征吗 import os, sys import textwrap INFILE="in.txt" OUTFILE="out.txt" with open(INFILE, 'r') as file: lines = file.readlines() fo

我一直在试验Python textwrap模块,以包装长行文本。 我注意到终端的打印输出看起来很好,换行符工作正常。但当我写入文件时,会看到略有不同的输出。 我想知道,这是印刷与书写的一个已知特征吗

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.

我最终使用了这个代码。它使用print()并将输出发送到文件,效果良好

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



关于如何将屏幕打印输出发送到文本文件,有什么想法吗?我希望通过使用print()来重现我得到的布局,但是使用fp.write()
print()
在默认情况下为所有内容添加新行。但是使用
write()。一个技巧是在我的脚本中只使用
print()
,然后将输出重定向到一个文件:
/linewrap.py in.txt | tee out.txt
,因为我使用的是python 2.7,所以我需要包含以下语句:
from uuu future uu u导入打印u函数