sneaky
sneaky

Reputation: 2201

How to erase all text from a file using python, but not delete/recreate the file?

I want to basically copy whats from the clipboard and paste it in a file in utf-8 encoding, but what ever I try, the file has the '?' symbols in it and is Anscii encoding...

But what I found out is, if there is a file that's already in utf-8 encoding, then whatever I paste in it manually (deleting whats there already), wont have the '?' in it.

So if there is a way to clear content in a utf-8 file, then copy whats from the clipboard and write it to that file then that would be great.

If I create the file, it's always ends up being Ancii...

Now I already know how to copy from clip board and write it to a file, its just how to clear a file which is confusing...

Upvotes: 2

Views: 12905

Answers (2)

shashwat
shashwat

Reputation: 1002

The easiest solution I can think of (with my limited knowledge) is to make the file in Python in binary mode, since binaries support UTF-8 encoding:

fo=open("file.dat","wb")
# The 'b' flag tells python to make it binary

This should work with what you want to do.

To erase the file, just give an existing file name with 'w' and 'b' flags.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Opening the file in write/read mode (w+) will truncate the file without rewriting it if it already exists.

Upvotes: 5

Related Questions