python-3.x - 如何将文本文档的内容随机复制到我的剪贴板
问题描述
这是我原来的问题
以下脚本将文本复制/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/document1.txt
/home/my_files/document2.txt
/home/my_files/document3.txt
/home/my_files/image1.jpg
/home/my_files/image2.png
我想创建一个脚本,将三个文本文档之一的内容随机复制/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
我很困惑。
解决方案
以下成功将 /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 坚持上面的脚本可以正常工作。我不知道我做错了什么,但是当我指出上面的脚本不能正常工作时,我一定是做错了什么。
推荐阅读
- json - 使用 React 功能组件中的 setState 更新空对象 {}
- javascript - 状态没有正确更新
- javascript - JS 问题:如何让我的 0 级在我的聊天提示中流到 1 级
- flutter - Flutter错误无法将元素类型'List'分配给列表类型'Widget'
- python - 如何从嵌套列表中删除子列表?
- java - 如何使用 MutliResoucrItemReader 为步骤设置动态块大小?
- swift - NSPredicate 优先返回值
- python - 为什么我在保存图像时会丢失通道以及如何避免它?
- java - 为什么总是多打印一行“年利率”,这个问题怎么解决?
- database - DynamoDB Schema 设计与复合键