首页 > 解决方案 > 如何将文本文档的内容随机复制到我的剪贴板

问题描述

这是我原来的问题

以下脚本将文本复制/home/my_files/document1.txt到我的剪贴板。

import pyperclip
path = '/home/my_files/document1.txt'
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)

假设/home/my_files/包含以下五个文件:

我想创建一个脚本,将三个文本文档之一的内容随机复制/home/my_files/到我的剪贴板中。

当然,以下脚本不起作用,它显示了我一直在试验的一些模块。

import glob,random,pyperclip
pattern = "*.txt"
path = random.choice((glob.glob(pattern))("/home/my_files/"))
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)

你对我有什么相关的建议吗?

我在上面的原始问题中添加了后续内容

当我尝试@Jacob Lee 创建的以下解决方案时...

import glob
import random
import pyperclip

files = [os.path.abspath(f) for f in glob.glob("./home/my_files")]
path = random.choice(files)
with open(path) as f:
    pyperclip.copy(f.read())

我收到以下错误消息...

Traceback (most recent call last):
  File "abc.py", line 3, in <module>
    path = random.choice(glob.glob(pattern))
  File "/usr/lib/python3.8/random.py", line 290, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

其他人向我建议了以下脚本...

import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)

但是那个脚本也不起作用。运行该脚本时收到以下错误...

Traceback (most recent call last):
  File "abc.py", line 3, in <module>
    path = random.choice(glob.glob(pattern))
  File "/usr/lib/python3.8/random.py", line 290, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

我很困惑。

标签: python-3.x

解决方案


以下成功将 /home/my_files/ 中的随机文本文件的全部内容复制到我的剪贴板

import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)

感谢@Asocia

感谢@Asocia 坚持上面的脚本可以正常工作。我不知道我做错了什么,但是当我指出上面的脚本不能正常工作时,我一定是做错了什么。


推荐阅读