首页 > 解决方案 > 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

标签: python

解决方案


只需打开现有文件并阅读这些行。假设您要替换始终跟随“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()

推荐阅读