Pyperclip not pasting new lines?

2020-04-27 19:55发布

问题:

I'm trying to make a simple script which takes a list of names off the clipboard formatted as "Last, First", then pastes them back as "First Last". I'm using Python 3 and Pyperclip.

Here is the code:

import pyperclip
text = pyperclip.paste()
lines = text.split('\n')
for i in range(len(lines)):
    last, first = lines[i].split(', ')
    lines[i] = first + " " + last
text = '\n'.join(lines) 
pyperclip.copy(text)

When I copy this to the clipboard:

Carter, Bob
Goodall, Jane

Then run the script, it produces: Bob CarterJane Goodall with the names just glued together and no new line. I'm not sure what's screwy.

Thanks for your help.

回答1:

Apparently I need to use '\r\n' instead of just '\n'. I don't know exactly why this is but I found that answer on the internet and it worked.



回答2:

To include newlines in your file, you need to explicitly pass them to the file methods. On Unix platforms, strings passed into .write should end with \n. Likewise, each of the strings in the sequence that is passed into to .writelines should end in \n. On Windows, the newline string is \r\n. To program in a cross platform manner, the linesep string found in the os module defines the correct newline string for the platform:

>>> import os
>>> os.linesep # Unix platform
'\n'

Souce: Illustrated Guide to Python 3