【问题标题】:python .write is making unwanted spaces between linespython .write 在行之间产生不需要的空格
【发布时间】:2022-01-05 08:40:37
【问题描述】:

我在 python 中遇到了一个问题,即从剪贴板将文件写入为 txt 文件。我正在使用 pyperclip.paste() 从剪贴板获取数据并写入文件。但是当我在 python 中使用 .write 命令创建 .txt 文件时,文本文件的行之间有很大的空格,我不明白为什么。我将分享我的意思的屏幕截图。

这是我使用的代码。

import pyperclip

file = open("file.txt", "w")
print(pyperclip.paste())
file.write(pyperclip.paste())
file.close()

这是我试图制作文本文件的剪贴板内容。它具有正确的制表符和新的行格式。仅供参考,这是我使用 selenium 从 quizlet“复制文本”中获取的内容,但无论我如何复制文本(记事本、单词),问题仍然存在。

Extrinsic pathway       cascade of clotting factors in blood that has escaped the vascular system to form a clot on the outside of the injured vessel

Common Pathway  where intrinsic and extrinsic pathways converge

Initiation of clotting pathway  tissue damage cause by factor 7a in extrinsic pathway

Thrombin Activation     factor 5,8,11,13

Thrombin        - activate platelets
- convert fibrinogen to fibrin
- activate factors and Protein C

Tissue factor   initiates the extrinsic pathway when released in response to tissue damage

Calcium needed  extrinsic 9-10, 10-2
intrinsic 11-9, 9-10, 10-2

image of pasting my clipboard content into notepad粘贴到记事本时格式正确

image of vscode terminal我也用了print(pyperclip.paste()),文字输出正常。

the file.txt written by python with incorrect format 当我使用 file.write(pyperclip.paste()) 写入文件时,行之间不应该有空格。

发生了什么事?我该如何解决这个问题,并保存正确的文本文件?

【问题讨论】:

  • 尝试print(repr(pyperclip.paste())) 查看所有字符,尤其是行尾。

标签: python file write pyperclip


【解决方案1】:

我的猜测是这些行的末尾有一个\r\n,Windows 将其视为一个新行,也许 pyperclip 将其视为两个。

您可以通过使用“splitlines”拆分文本然后将其粘贴在一起并每行使用一个 \n 来解决此问题:

"\n".join(pyperclip.paste().splitlines())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 2020-02-09
    • 2016-05-06
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    相关资源
    最近更新 更多