'python .write is making unwanted spaces between lines

I'm running into a problem in python about writing files as txt files from clipboard. I'm using pyperclip.paste() to get the data from clipboard and write the file. But when I use .write command in Python to create a .txt file, the text file has huge spaces between lines and I don't understand why. I will share screenshots of what I mean.

Here are the codes I used.

import pyperclip

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

This is the content of my clipboard that I'm trying to make a text file. It has correct tab and new line format. FYI, it is the content I grab from quizlet "copy text" using selenium, but regardless of how I copy the text (notepad, word), problem persists.

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 when pasted into notepad, it is the correct format

Image of VSCode terminal I also used print(pyperclip.paste()), and the text output is normal.

The file.txt written by python with incorrect format when I use file.write(pyperclip.paste()) to write the file, there are spaces between lines where there shouldn't be.

What is going on? How would I fix this problem, and save the correct text file?



Solution 1:[1]

My guess would be that the lines have a \r\n at the end, Windows treats this as a single new line, maybe pyperclip is treating this as two.

You can resolve this by splitting the text using 'splitlines' then sticking it back together with a single \n per line:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JeffUK