python - Python truncate 函数未按预期工作
问题描述
我对python中的截断函数有点困惑。truncate 函数不应该清空文件并仅显示第二行输入吗?但是在我的文件中,第一行和第二行输入都在程序结束后的文件中。
文件中的预期输出
Line2 input
文件中的当前输出
Line1 input Line2 input
如果我使用 .truncate(0) 这就是我在文件中得到的
from sys import argv
script, filename = argv
print(f"Erasing the file {filename}")
print("Opening the file...")
# This empties and overrides the file when opening in w mode use 'a' to append to file
target = open(filename, 'w')
line = input("Input a line")
target.write(line)
print("Truncating ie erasing the file...")
target.truncate()
line2 = input("Input another line")
target.write(line2)
target.close()
请帮忙
解决方案
推荐阅读
- c++ - 如何声明具有相同类的属性?
- java - 如何正确初始化数组以使线程不超过它(矩阵示例)?
- javascript - Parallax.js 中的缩放图像
- r - Min函数在循环inR中不断返回错误值
- excel - 在 Excel 中使用 vba 编辑器更新和转换查询
- css - Svg 线半实线,半虚线
- python - 如何将 Python Flask CAS 服务器连接到 Angular 应用程序?
- mongodb - mongodb中嵌套对象数组的聚合查询
- blockchain - NEAR cli 合约调用有效,但从具有相同参数的 js sdk 调用时失败
- javascript - 如何从javascript中的URI中提取文件名?