python - Edit specific line at specific position in Text file in Python
问题描述
I have two variables x1=123.12 and y1=123.45 which holds user entered values .Now I have a text file in which I have to change current 245.42 and 130.32 with the variable x1 and y1 which holds user entered values.So how can I modify text file in python?
#text file:
var char12
name andy jordan
home illino
w1 345 3456
p1 346 2123
addmoney 245.42
netmoney 130.32
解决方案
只需打开现有文件并阅读这些行。假设您要替换始终跟随“addmoney”和“netmoney”的值,您可以找到这些行并使用re.sub()
将这些值替换到这些行中。请记住,您不能简单地就地覆盖文本文件,因此您可以存储修改后的行,然后在最后重新创建一个新文件,如下所示:
x1 = 123.12
y1 = 123.45
import re
with open('mytextfile.txt', 'r') as f:
lines = f.readlines()
for i, l in enumerate(lines):
if l.startswith('addmoney'):
lines[i] = re.sub(r'[0-9.]+', str(x1), lines[i])
elif l.startswith('netmoney'):
lines[i] = re.sub(r'[0-9.]+', str(y1), lines[i])
out = open('modifiedtextfile.txt', 'w'); out.writelines(lines); out.close()
推荐阅读
- scala - 为什么我需要使用函数签名扩展我的案例类才能在 Sparks rdd.mapPartition 中工作?
- python - pymongo 在大型集合上更新相同的字段值
- python - 如何在 Python 中的 list 对象中使用 where
- amazon-web-services - 如何使用 AWS S3 .NET 开发工具包 AmazonS3ControlClient 创建批处理操作?
- matlab - 每个线段点的垂直线 - Matlab
- android - 如何将蓝牙控制器连接到 Pixel 4 手机
- reactjs - Ktor 后端的 CORS 问题
- tizen - 如何在 Tizen 原生 API 应用程序中的大圆圈 genlist 中实现快速导航?
- angular - *ngFor 中的对象键值数组,用于角度 7
- javascript - React - 使用基于变量的三元运算符的条件输出