gpt4 book ai didi

python - 为什么 read() 函数会删除我文件中的所有数据?

转载 作者:行者123 更新时间:2023-11-28 19:42:30 25 4
gpt4 key购买 nike

我正在做一个项目,我必须在其中制作一个多剪贴板。以下是它将执行的操作:

这个多剪贴板将通过终端运行。它将创建一个名为 clipboardd 的文件,并将所有复制的文本保存在那里。该人可以根据需要添加任意数量的复制文本,也可以根据需要清除多剪贴板。

代码如下:

import pyperclip
import sys

jim=open('multiclipboardd','w')

#This will copy text to the multiclipboard
if len(sys.argv)==2 and (sys.argv[1].lower())=='save':
jim=open('multiclipboardd','a')
jim.write(pyperclip.paste())
jim.write('\n')
print('The text has been pasted to the multiclipboard!')
jim.close()


#This will read text from the multiclipboard
elif len(sys.argv)==2 and (sys.argv[1].lower())=='list':
kk=open('multiclipboardd')
print(kk.read())


#This will delete the text of the multiclipboard
elif len(sys.argv)==2 and (sys.argv[1].lower())=='delete':
jim=open('multiclipboardd','w')
jim.write('')
print('The clipboard has been cleared!')
#jim and kk are just variables

此文件的名称是 Panda.py

在终端中调用 python panda.py save 应该将当前复制的文本保存到名为 clipboardd 的文件夹中,它的确如此!当我尝试调用它时,它工作得很好。

但是,当我尝试在终端中运行 python panda.py list 时,预计它会在屏幕上打印所有复制的单词,但它会全部删除!假设在调用 python panda.py list 之前,clipboardd 有 110 个字母。然后在调用 python panda.py list 后,它有 0 个字母!

为什么 read() 会删除文件 clipboardd 中的所有字符?

最佳答案

每次使用“w”模式打开文件时,它都会覆盖文件中的所有现有数据。read() 没有这样做。为防止这种情况,请每次都使用“a”模式打开文件。希望这会有所帮助。

关于python - 为什么 read() 函数会删除我文件中的所有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com