简体   繁体   English

如何使用 python 替换文本文件中字段中的值

[英]How to use python to replace a value in a field in a text file

I have a file that looks like this:我有一个看起来像这样的文件:

;
[ atomtypes ]
  opls_BZCG BCG1    78.113999   0.000   A   2.9310E-01  1.9173E-01
[ moleculetype ]
; Name      nrexcl
BZCG        1
[ atoms ]
;   nr  type    resnr   residue atom    cgnr    charge  mass
    1   opls_BZCG   1       BZCG    BCG1        1       0       78.113999

I am trying to use python to change the values in the second last and last field under the [ atomtypes ] title.我正在尝试使用 python 更改[ atomtypes ]标题下倒数第二个和最后一个字段中的值。 The deal is that I am running a code which iteratively updates this file, so I specifically want that field to be targeted, not the regular expression "2.931E-01" or "1.9173E-01".交易是我正在运行一个迭代更新此文件的代码,因此我特别希望该字段成为目标,而不是正则表达式“2.931E-01”或“1.9173E-01”。 I know we can use things like awk, but I was wondering if this is possible from python itself.我知道我们可以使用 awk 之类的东西,但我想知道这是否可以从 python 本身实现。

This is what I am doing so far:到目前为止,这就是我正在做的事情:

flag = 0
with open("file.itp") as f: 
  for line in f:
     iterable = line.strip().split()
        if flag:
            line.strip().split()[5] = sigma 
            line.strip().split()[6]) = eps 
            print("epsilon is {} and sigma is {}".format(eps, sigma))
        if "atomtypes" in iterable:
            flag = 1
        else:
            flag = 0

    f.close()

I am changing the value in python, but I am not able to send that change to the file itself.我正在更改 python 中的值,但我无法将该更改发送到文件本身。 How do I pull this off?我该如何解决这个问题?

Any advice you have would be appreciated!您的任何建议将不胜感激!

Use enumerate on lines so we can access current line and next line在行上使用枚举,以便我们可以访问当前行和下一行

Code代码

def update_line(filenm, eps, sigma):
    with open(filenm, 'r') as fin:
        lines = fin.readlines()
        
        for idx, line in enumerate(lines):
            if "atomtypes" in line:
                # Current line has marker, so change next line (i.e. index idx + 1)
                #   Split next line into fields 
                #   split from end so so only have three fields, namely:
                #    1) everything before next to last field, 
                #    2) next to last field, 
                #    3) last field)
                arr = lines[idx+1].rsplit(' ', maxsplit = 3)
                arr[-3], arr[-1] = f"{eps:e}", f"{sigma:e}"
                lines[idx+1] = ' '.join(arr) + "\n"  # last_val dropped the '\n' so add back
                break
        
    with open(filenm, 'w') as fout:
        # Updated lines placed back into file
        fout.writelines(lines)
    

Test测试

update_line('test.txt', 4.573133E-02, 8.2737123E-01)

File test.txt prior:文件 test.txt 之前:

;
[ atomtypes ]
  opls_BZCG BCG1    78.113999   0.000   A   2.9310E-01  1.9173E-01
[ moleculetype ]
; Name      nrexcl
BZCG        1
[ atoms ]
;   nr  type    resnr   residue atom    cgnr    charge  mass
    1   opls_BZCG   1       BZCG    BCG1        1       0       78.113999

File test.txt after文件 test.txt 之后

;
[ atomtypes ]
  opls_BZCG BCG1    78.113999   0.000   A   4.573133e-02  8.273712e-01
[ moleculetype ]
; Name      nrexcl
BZCG        1
[ atoms ]
;   nr  type    resnr   residue atom    cgnr    charge  mass
    1   opls_BZCG   1       BZCG    BCG1        1       0       78.113999

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

相关问题 如何用python中的最新值替换文本文件中的一行? - How to replace a line in a text file with the latest value in python? 如何使用 %s 替换 python 文件中的文本? - How can I use %s to replace text within a file in python? 如何在python中搜索和替换文本文件的多个值? - how to search and replace for multiple value of text file in python? Python - 如何替换文本文件中值未知的字符串? - Python - How to replace a string in a text file where value is not known? 如何使用Pandas DataFrame字段在Python中的另一个字段中正则表达式替换文本? - How to use a pandas dataframe field to regex-replace text in another field in Python? 如何使用str.replace从旋转框获取值,然后在文本文件中替换该值的实例? - How can I use a str.replace to take a value from a spinbox, and then replace an instance of that value in a text file? "如何使用Python编辑Python文件中一行代码的文本值?" - How to use Python to edit the text value of a line of code in Python file? 如何在Python中用其他值替换文件中的值 - How to replace a value in a file with other value in Python 如何替换 xml 文本以使用 Python - How to replace the xml text to use Python 如何使用正则表达式替换 Python 中文本中的标记 - How to use regex to replace tokens in text in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM