python - 如何在python中覆盖文本文件中的一行文本
问题描述
name email phonenumber
eric example@gmail.com 01381031
tuna tuna@gmail.com 1571051
以上是personal_details.txt
def personal(userid):
print("Modify personal details")
newemail = input("Enter your new email: ")
newphone = input("Enter your new phone:")
with open("personal_details.txt", "r+") as file:
for line in file:
line = line.split()
if userid == line[0]:
file.seek(0)
file.write(" " + newemail + " " + newphone)
file.truncate()
我正在创建用户可以修改详细信息的配置文件系统。我想覆盖文件第 [2] 行和第 [3] 行中的文本,但它一直覆盖整个文件。我对python很陌生,所以我真的需要一些帮助来解决这个问题。
解决方案
首先将文本复制到一个新变量并使用 .replace 替换所需的单词,然后您可以覆盖文本文件
推荐阅读
- python-3.x - 在 Python 的 for 循环中未激活 Break
- flutter - 如何在 TextField() Flutter 上设置范围数值
- c# - 在 Castle Windsor 中注册泛型接口的多个实现
- sas - 为什么我收到错误:错误:值 02 不是有效的 SAS 名称。在这个简单的查询中
- pandas - 在 Pandas 中,基于两组索引连接来自两个数据帧的值
- c++ - 使用基于范围的 for 循环和指针向量时的 C++ 错误
- powershell - 使用 PowerShell 替换程序中的代码源
- mongodb - 与 mongodb 连接时出现 Apache solr 错误
- osgi - Karaf Cellar:安装 Kar 文件时出现问题 -> Maven 找不到工件
- python - 如何通过某些功能在 PyQt5 中切换屏幕?