我有一个文本文件,我想在Python中擦除。我怎么做呢?
当前回答
以“写”模式打开一个文件可以清除它,你不需要特别地写入它:
open("filename", "w").close()
(你应该关闭它,因为文件自动关闭的时间可能是特定于实现的)
其他回答
由于文本文件是顺序的,所以不能直接擦除其中的数据。你的选择是:
The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name. You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase. Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.
看看seek/truncate函数/方法来实现上面的任何想法。Python和C都有这些函数。
以“写”模式打开一个文件可以清除它,你不需要特别地写入它:
open("filename", "w").close()
(你应该关闭它,因为文件自动关闭的时间可能是特定于实现的)
你必须覆盖这个文件。在c++中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
当使用open("myfile.txt", "r+")作为my_file:时,我在myfile.txt中得到奇怪的0,特别是因为我先读取文件。为了让它工作,我必须首先用my_file.seek(0)将my_file的指针更改为文件的开头。然后我可以执行my_file.truncate()来清除文件。
在python中:
open('file.txt', 'w').close()
或者,如果你已经打开了一个文件:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录