我有一个文本文件,我想在Python中擦除。我怎么做呢?
当前回答
当使用open("myfile.txt", "r+")作为my_file:时,我在myfile.txt中得到奇怪的0,特别是因为我先读取文件。为了让它工作,我必须首先用my_file.seek(0)将my_file的指针更改为文件的开头。然后我可以执行my_file.truncate()来清除文件。
其他回答
写入和读取文件内容
def writeTempFile(text = None):
filePath = "/temp/file1.txt"
if not text: # If not provided return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
这对我很有效
在python中:
open('file.txt', 'w').close()
或者,如果你已经打开了一个文件:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
正如@jamylak所建议的,包含上下文管理器优点的一个好的替代方案是:
with open('filename.txt', 'w'):
pass
当使用open("myfile.txt", "r+")作为my_file:时,我在myfile.txt中得到奇怪的0,特别是因为我先读取文件。为了让它工作,我必须首先用my_file.seek(0)将my_file的指针更改为文件的开头。然后我可以执行my_file.truncate()来清除文件。
这是我的方法:
使用r+模式打开文件 使用file. Read()从文件中读取当前数据 使用file.seek(0)将指针移到第一行 使用file.truncate(0)从文件中删除旧数据 先写新内容,再写之前用file.read()保存的内容
所以完整的代码是这样的:
with open(file_name, 'r+') as file:
old_data = file.read()
file.seek(0)
file.truncate(0)
file.write('my new content\n')
file.write(old_data)
因为我们使用的是打开,文件会自动关闭。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录