Reputation: 415
I was doing a project in which I had to make a multiclipboard.
It will create a file and save all the copied texts over there. The user can add as many copied texts as they want and they also can clear the multiclipboard.
Here's the code:
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!')
The name of this file is panda.py
. Calling python panda.py save
in the terminal should save the curent copied text to a file named clipboardd
and it does!
However, when I try to run python panda.py list
in the terminal, it is expected that it would print al the copied words on the screen, but it deletes them all! Suppose that before calling python panda.py list
, clipboardd
has 110 letters. Then after calling python panda.py list
, it has 0 letters!
Why is the list
command deleting all the characters inside the file? Is it the read()
function?
Upvotes: 4
Views: 1367
Reputation: 481
read()
is not truncating your file.
The unconditional jim = open('multiclipboardd', 'w')
at the top of your file is.
If you don't want it to delete your content, replace the 'w'
with an 'a'
.
Upvotes: 1
Reputation: 555
When you do jim = open('multiclipboardd', 'w')
at the top of your program, it truncates the original file and erases it. That's why your file's getting erased.
Also, when you open files you should .close()
them or use a context manager.
Upvotes: 5
Reputation: 799
Each time you open your file with 'w'
mode, it overwrites all the existing data in the file.
read()
isn't doing this. To prevent this, open the file with 'a'
mode.
Upvotes: 7