python - 如何在文件的特定位置插入而不是覆盖
问题描述
我正在尝试使用以下方法在文件的特定位置插入一些文本:
with open("test.txt","r+") as f:
f.seek(5)
f.write("B")
但这会用新数据(“B”)覆盖位置 5 的字符,而不是插入它。
例如,如果我有
AAAAAAAAAA
在文件中test.txt
并运行我得到的代码AAAAABAAAA
而不是AAAAABAAAAA
(五个A
必须在之后B
)
如何在文件的所需位置插入而不是覆盖?
解决方案
这对我有用:
with open("test.txt","r+") as f:
f.seek(5) #first fseek to the position
line=f.readline() #read everything after it
f.seek(5) #since file pointer has moved, fseek back to 5
f.write("B") #write the letter
f.write(line) #write the remaining part
Original : AAAAAAAAAA
After : AAAAABAAAAA
推荐阅读
- python - 无法使用 [] 和 '' 读取 csv 文件
- gitlab - Katalon 与 gitlab 的集成
- javascript - 在 IE 10 中请求全屏
- python - 由于 ModuleNotFoundError,Flask 无法使用 Docker 启动服务器:没有名为“wsgi”的模块
- c# - AAS 模型暂停和恢复后,尝试打开 ADOMD.net 连接返回 307 响应
- fastlane - 如何根据最后批准的 iOS 版本增加版本号
- html - 如何使用 CSS 反转背景图像的颜色?
- snowflake-cloud-data-platform - 如何查看已应用的任何用户级网络策略?
- python - 使用 defaultdict 添加/更新 dict
- php - 带有文档处理/扫描的 Wordpress 搜索