简体   繁体   English

在 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?我有两个变量x1=123.12 和 y1=123.45保存用户输入的值。现在我有一个文本文件,我必须在其中更改当前的245.42 和 130.32与保存用户输入值的变量x1 和 y1。那么我该如何修改python中的文本文件

#text file:

var char12
name andy jordan
home illino

w1 345 3456 
p1 346 2123
addmoney 245.42
netmoney 130.32

Simply open the existing file and read the lines.只需打开现有文件并阅读行。 Assuming that you want to replace the values that always follow 'addmoney' and 'netmoney', you can locate those lines and use re.sub() to substitute the values into those lines.假设您要替换始终跟在 'addmoney' 和 'netmoney' 之后的值,您可以找到这些行并使用re.sub()将这些值替换到这些行中。 Keep in mind that you can't simply overwrite text files in-place, so you store the modified lines and then recreate a new file at the end, like so:请记住,您不能简单地就地覆盖文本文件,因此您可以存储修改后的行,然后在最后重新创建一个新文件,如下所示:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM