Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

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?

like image 844
M.Hamel Avatar asked Nov 16 '25 19:11

M.Hamel


2 Answers

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.

like image 129
Debanik Dawn Avatar answered Nov 18 '25 09:11

Debanik Dawn


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.

like image 37
SH7890 Avatar answered Nov 18 '25 07:11

SH7890



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!