The clipboard (English: clipboard) is a shared memory area on a computer that can temporarily store data. (From Wikipedia)
When do you want to manipulate the clipboard in Python? You might think that.
For example, consider this situation.
I want to paste a dataframe (table table) processed by Python into Excel. If you have this Excel file on your computer, you can write it directly in Python, but the file is on your company's server ** and it's difficult to access it directly from Python ... ** **
In such a situation, it is convenient to ** copy the dataframe to the clipboard and then manually open and paste the corresponding Excel file **.
Use a module called ** pyperclip ** to copy to or paste from the clipboard.
This pyperclip is very simple, pyperclip.copy ()
and pyperclip.paste ()
are almost everything.
operation | function |
---|---|
Copy to clipboard | pyperclip.copy() |
Paste from clipboard | pyperclip.paste() |
For example, if you copy a table in Excel and paste it in another place in Excel, it will be a table properly.
It may be obvious, but do you feel a little strange? How does the clipboard hold this "tabular format"?
Let's check. I have an Excel table like the one below.
Copy A1 to E6 of this table to the clipboard with Crtl + C. Then, in Python, execute the following to check the contents of the clipboard.
import pyperclip
pyperclip.paste()
Execution result
'Takeo Oi\t Oitakeo\t man\t1960/8/30\t Chiba\r\n Keiko Nagai\t Nagai Keiko\t woman\t1999/5/21\t Kochi prefecture\r\n Mika Mogi\t Mogi Mika\t woman\t1989/3/27\t Saitama prefecture\r\n Takako Nasu\t Nasta Kako\t woman\t1981/9/29\t Hiroshima prefecture\r\n Shoichi Sugiura\t Sugiura Shoichi\t man\t1991/10/31\t Hyogo prefecture\r\n'
You can see that the next column is separated by ** tab (\ t) ** and the next row is separated by ** line feed code (\ r \ n) **.
In other words, create a character string separated by a tab (\ t) and a line feed code (\ r \ n) like this, copy it to the clipboard with pyperclip.copy ()
, and then press Ctrl + V to Excel. It can be pasted in tabular format.
let's do it.
Execute as below and copy the character string you want to paste to the clipboard.
pyperclip.copy("Shigeru Sasaki\t Sasaxi gel\t man\t1964/2/13\wakayama prefecture\r\n Kanae Mita\t Mitaka Kanae\t woman\t1979/10/1\t Akita prefecture\r\n")
Then open Excel and paste it ...
You were able to paste it properly as a table!
Recommended Posts