M.Hamel M.Hamel - 1 year ago 65
Python Question

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

I was doing a project in which I had to make a multiclipboard. Here's what it'll do:

This multiclipboard would run through the Terminal. It will create a file named clipboardd and save all the copied texts over there. The person can add as many copied texts as he wants and he also can clear the multiclipboard if he wants to.

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!')
#jim and kk are just variables


The name of this file is Panda.py

Calling
python panda.py save
in the Terminal should save the curent copied text to a folder named clipboardd and it does! This works perfectly fine when I try to call it.

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
read()
deleting all the characters inside the file clipboardd?

Answer Source

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 everytime. Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download