简体   繁体   English

如何使用python删除文件中的所有文本,而不删除/重新创建文件?

[英]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 '?' 我基本上想从剪贴板复制内容,然后将其粘贴到utf-8编码的文件中,但是我尝试过该文件是否带有'?' symbols in it and is Anscii encoding... 其中的符号,并且是Anscii编码...

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 '?' 但是我发现的是,如果有一个文件已经采用utf-8编码,那么无论我手动粘贴到其中(删除已存在的内容),都不会带有“?” 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. 因此,如果有办法清除utf-8文件中的内容,然后复制剪贴板中的内容并将其写入该文件中,那将是很好的。

If I create the file, it's always ends up being Ancii... 如果我创建文件,则总是以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... 现在我已经知道如何从剪贴板复制并将其写入文件,它只是如何清除令人困惑的文件...

如果文件已经存在,则以写/读模式( w+ )打开文件将截断该文件而不进行重写。

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: 我可以想到的最简单的解决方案(以我有限的知识)是使用二进制模式在Python中制作文件,因为二进制文件支持UTF-8编码:

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. 要擦除文件,只需给现有文件名加上“ w”和“ b”标志即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM