简体   繁体   English

如何通过python删除文本文件中的所有字符

[英]How to delete all characters in text file by python

I have a text file namefile.txt which has more character. 我有一个文本文件namefile.txt ,其中包含更多字符。 I want to delete all text and keep the file in order to see nothings when we open namefile.txt after run the python script? 我想删除所有文本并保留文件,以便在运行python脚本后打开namefile.txt时看不到任何内容?

This will do it. 这样就可以了。 Opening a file with write permission conceptually clears previous data. 从概念上讲,打开具有写许可权的文件会清除以前的数据。

open('namefile.txt', 'w').close()

Simply open the file in write mode and close it 只需在写入模式下打开文件并关闭它

f = open('myfile.dat', 'w')
f.close()

如果要保持文件打开,也可以调用:file.truncate()

暂无
暂无

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

相关问题 如何使用 python 脚本删除文件每行中“==”后的所有字符并更新文件? - How to delete all characters after a “==” in each line of a file and update the file, using python script? Python - 如何删除某些符号后所有行中的所有字符? - Python - how to delete all characters in all lines after some sign? 如何从python中的文本文件中删除所有带有大写字母和数字和特殊字符的行以及所有长度超过10个字符的行 - How to remove all lines with caps AND digits AND special characters AND all the lines longer than 10 characters from a text file in python 如何使用python删除文件中的所有文本,而不删除/重新创建文件? - How to erase all text from a file using python, but not delete/recreate the file? Python - 如何删除子字符串中直到并包括关键字的所有字符 - Python - How to delete all characters in a sub string up to and including a keyword 如何在python中读取带有特殊字符的文本文件 - How to read a text file with special characters in python 如何使用python分隔文本文件中的字符 - How to separate characters in text file with python 如何删除文本文件中的非ASCII字符? - How to delete non-ASCII characters in a text file? 获取文本文件中存在的所有唯一字符的列表(例外)(Python) - Get a listing of all unique characters present in a text file (with exceptions) (Python) 如何从python中的文本文件中删除行 - how to delete line from text file in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM