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

Why is the read() function deleting all the data in my file?

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

此多剪贴板将 运行 通过终端。它将创建一个名为 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 中的所有字符?

当您在程序顶部执行 jim=open('multiclipboardd','w') 时,它会截断原始文件并将其删除。这就是你的文件被删除的原因。

此外,当您打开文件时,您应该 .close() 或使用 context manager.

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

正如 Amadan 所说,read() 不会截断您的文件。

文件顶部的无条件 jim=open('multiclipboardd','w') 是。

如果您不希望它删除您的内容,请将 'w' 替换为 'a'