簡體   English   中英

Python textwrap:終端打印與寫入文件的不同結果

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

我一直在嘗試使用 Python textwrap 模塊來換行長文本。 我注意到打印到終端的 output 看起來不錯,自動換行按預期工作。 但是當我寫入文件時,看到的 output 略有不同。 我想知道這是打印與寫入的已知功能嗎?

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

在.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() 並將 output 發送到文件並且運行良好。

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


是的, print()write()是有區別的。 幾個:他們在這里:

  • print()
    • 是內置的全局function
    • 默認輸出到stdout (但可以使用fp= arg 更改)。
    • 默認情況下向每個字符串添加一個換行符 ( \n )(但可以使用end= arg 進行更改)。
  • write()
    • 是一個文件object的方法(綁定函數)
    • 僅在該文件 object 上輸出
    • 不添加換行符; 您必須通過明確將換行符添加到字符串或在 write 語句后插入額外的fp.write("\n")來自己完成此操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM